Aminesrine
Aminesrine

Reputation: 2140

Global variable with jquery

I have a js file test.js that contains a global variable global_var and a function fn1() that changes the variable global_var:

var global_var="initial_value";
function fn1(){
    global_var="Value1";
    alert("global_var="+global_var);
}

then I execute the fn1() from my page1.html that sends me to page2.html:

<li><a href="page2.html" onclick='fn1();'></a></li>//this returns "global_var=Value1"

Then, in page2.html I want to use the variable global_var, but the continous of global_var is not changed, it's "initial_value"!!

<script src="test.js"></script>
<script>
   $('#mypage').live('pageshow', function(event) {
   alert(global_var); //this returns "initial_value"!!! 
});
</script>

Upvotes: 4

Views: 8683

Answers (4)

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76870

Every time a new page is loaded javacript is re-initialized and so any change to the variable is lost. You could save tha value in a cookie and retrieve that in page2

page1

var global_var="initial_value";
function fn1(){
    global_var="Value1";
    alert("global_var="+global_var);
    $.cookie('global_var', global_var);
}

page 2

<script src="test.js"></script>
<script>
   $('#mypage').live('pageshow', function(event) {
   var global_var = $.cookie('global_var');
   alert(global_var); //this returns "initial_value"!!! 
});

</script>

this requires this plugin https://github.com/carhartl/jquery-cookie

Upvotes: 3

Shahdat
Shahdat

Reputation: 5473

If its matter of two pages only you can use simple querystring

Page1

var k="initial_value";
function fn1(){
  k="Value1";
  //  alert("k="+k);
  location.href='page2.html?k='+k;
}

Page2

function querystring(key) {
   var re=new RegExp('(?:\\?|&)'+key+'=(.*?)(?=&|$)','gi');
   var r=[], m;
   while ((m=re.exec(document.location.search)) != null) r.push(m[1]);
   return r;
}

<script>
   $('#mypage').live('pageshow', function(event) {
   alert(querystring('k'));  
});

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1073968

"Global" variables in JavaScript on browsers are really page-wide variables. They only exist as long as the window object they were created on exists (because all global variables are properties of window). When you change pages, the old window object is destroyed and a fresh new one is created, so your variable no longer exists.

To persist information between pages, consider:

  • Using a cookie.
  • Using HTML5 "local storage" (note that IE7 and earlier don't have this, but IE8 and up do; some mobile browsers may not).
  • Using server-side state (but this doesn't scale massively well).

Upvotes: 2

Hans Wassink
Hans Wassink

Reputation: 2577

You dont call the function in page2. Every time you load to an other page your JS will reset... Save it in a SESSION or locally for example if you want to keep it alive!

Upvotes: 2

Related Questions