0

I have an HTML page (courses.html) that shows a list of courses. These courses are loaded from a database by an AJAX call into the array "courses" defined as global variable in script_1.js. Once I go to the page of a specific course in course.html I want to be able to pass this array to script_2.js to mantain the order of the courses and navigate them without having to perform the AJAX call again.

How I can pass this global variable or how I can manage this?

mattsven
  • 22,305
  • 11
  • 68
  • 104
pool
  • 91
  • 1
  • 1
  • 8

3 Answers3

3

You have the following option for passing data from one page to the next:

  1. Cookie. Store some data in a cookie in page1. When page2 loads, it can read the value from the cookie.

  2. Local Storage. Store some data in Local Storage in page1. When page2 loads, it can read the value from the Local Storage.

  3. Server Storage. Store some data on your server on behalf of user1 on page1. When page2 loads, the server can either place that user1 data on page2 or page2 can request that data from the server via ajax.

  4. Query Parameter. When page2 is loaded from page1, a query parameter can be placed onto the URL as in http://www.example.com/page2?arg=foo and page2 can parse that query parameter from the URL when it loads.

  5. Common Parent Frame. If your page is framed by a common origin and you are not changing the top level URL, but just the framed URL, then you can store global data in the top level parent and that data can be accessed from the framed page, even as it goes from page1 to page2.

You can often use JSON as a string-based storage format for more complex data items like an array. JSON can be put into any of the above storage options.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
2

The way to approach this would to be use cookies.

An answer to a previous stack overflow question explains really well how to store javascript objects in cookies and how to retrieve them.

https://stackoverflow.com/a/11344672/1130119

Community
  • 1
  • 1
UsainBloot
  • 816
  • 6
  • 20
1

You have a couple of options:

1) If you are developing a Single Page Application (SPA): Create a global variable to store your courses, for example: window.courses = []; // fill with your data courses

then when you load your page 2 you could access to window.courses variable

(keep in mind that you could create a object app and store in it all variable that you need as: window.app = {}; window.app.courses = [] )

2) It's useful for SPA or classical web application: Save courses on localStorage, you could store the courses and retrieve in the next page (or download if localStorage.getItem('courses') will be undefined).

Jose Mato
  • 2,709
  • 1
  • 17
  • 18