0

Possible Duplicate:
Javascript global variable does not persist when navigate to another page (which also uses same js file)

I have a script

<script>

var pn=0;

function set()
{
pn=parseInt(pn)+1;
}
</script>

After the first execution of set, pn will be 1.

After the page is reloaded, pn retains its value of 1 so on the next execution of set it will be incremented to 2.

How can I preserve global variables across page reloads?

Community
  • 1
  • 1
Saswat
  • 12,320
  • 16
  • 77
  • 156

5 Answers5

3

You could save the value of pn into a cookie via jquery cookie. Set cookie:

$.cookie("pn", pn);

Get value from cookie:

$.cookie("pn");
simplyray
  • 1,200
  • 1
  • 16
  • 25
2

In short, you can't. There is no way to persist client side variables on a page reload.

I would suggest using either

jQuery cookie plugin (cookies)

or if your browsers supports HTML5:

HTML5 web storage (local-/session storage)

Johan
  • 35,120
  • 54
  • 178
  • 293
  • 1
    localStorage is better than cookies.. at least in my opinion... easier to use, too – Kat Cox Jan 17 '13 at 10:36
  • @KatCox At long as the browser supports it, and the data is intented to be used on client-side only - yes :) – Johan Jan 17 '13 at 11:06
1

You should use cookies, here is an example how you can achieve it:

var pn = 0;

function increment() {
  pn = parseInt(pn, 10) + 1;
  setCookie('pn', pn, 200);
  console.log(pn);
}

function setCookie(c_name,value,exdays) {
  var exdate=new Date();
  exdate.setDate(exdate.getDate() + exdays);
  var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
  document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name) {
  var i,x,y,ARRcookies=document.cookie.split(";");
  for (i=0;i<ARRcookies.length;i++) {
    x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
    y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
    x=x.replace(/^\s+|\s+$/g,"");
    if (x==c_name) {
      return unescape(y);
    }
  }
}

(function () {
  pn = getCookie('pn') || 0;
}());

Here is an example: http://jsbin.com/ucitul/3

Minko Gechev
  • 25,304
  • 9
  • 61
  • 68
0

You should store your value in a cookie, the querystring or the hashfragment and then get the value at the page load.

JohnJohnGa
  • 15,446
  • 19
  • 62
  • 87
0

I suggest using jquery cookie plugin. It's rather simple and will solve your problem

Eugeny89
  • 3,797
  • 7
  • 51
  • 98