0

So I am working on a shopping cart that does not use cookies.

In my first page (the store) I define several variables such as item quantities,item names,etc.

In my second page (the checkout) I need to access the variables from the first page and display them to the user. How can I do so?

Reuben Ward
  • 101
  • 1
  • 9
  • http://stackoverflow.com/questions/1981673/persist-javascript-variables-across-pages similar question. I think you hae to use cookie – Melissa Hie Nov 10 '14 at 07:28

2 Answers2

4

There is no way to do it in JavaScript without using the environment outside of the language itself. All variables will lose their values when the page reloads.

There are plenty of possible solutions though. Which one is best depends on your constraints:

  • Store them on the server (using ajax or similar).
  • Store them in local storage
  • Store them in a cookie
  • Avoid reloading the page (e.g. single page approach)
  • Put them in the URL and have the new page parse them from there.

Edit: recommendation

The easiest of the above would be to go with the local storage solution, as described by murli2308 below. Write a variable with localStorage.setItem("myVarName", "myVarValue") on the first page and read it with localStorage.getItem("myVarName") on the second page.

Jakob
  • 24,154
  • 8
  • 46
  • 57
  • Thanks for the quick answer. What one of these would you recommend personally? – Reuben Ward Nov 10 '14 at 07:34
  • The main problems with `localStorage` are 1) lack of support in IE 7, see http://caniuse.com/#search=localstorage 2) being per-domain, so if your page is under someone else’s domain, you would be sharing `localStorage` data with others under that domain. – Jukka K. Korpela Nov 10 '14 at 09:47
  • @JukkaK.Korpela: Absolutely, good point! When I said the "easiest" I meant just that; it's very easy to get started with it. Other alternatives above have other benefits and other disadvantages. – Jakob Nov 10 '14 at 10:16
0

You can use local storage of HTML5 to store the data.

 localStorage.setItem("key", "value");

Also if you want to use session storage you can use it

 sessionStorage.key = valuetoupdate;
murli2308
  • 2,976
  • 4
  • 26
  • 47