jquery - How can I pass data from an ajax request to a global variable? -


ok. i'm totally baffled. here's code:

$(document).ready(function(){ var newtoken = 1;  $.get("junk.php",     function(newtoken) {         alert(newtoken); // alerts "junk"     }); alert(newtoken); // alerts "1" }); 

as per comments, first alert of newtoken "junk" (the output of junk.php). once outside .get, newtoken reverts "1". need variable set output junk.php. not possible? i've tried everything, , searched everywhere.

thanks.

you're shadowing first newtoken variable new newtoken variable used argument:

problem:

$(document).ready(function(){ var newtoken = 1; // <== newtoken number 1  $.get("junk.php",     function(newtoken) { // <== newtoken number 2.                          //     since it's first argument                          //     in success function                          //     data returned.          alert(newtoken); // <== alerts data returned. newtoken number 1                           // shadowed, obscured, covered up...     }); alert(newtoken); }); 


work around... use different names, or arguments array:

solution:

$(document).ready(function(){ var newtoken = 1;  $.get("junk.php",     function() {  // <== don't shade newtoken                   //     use variable name "data"                   //     decided use arguments array kicks          alert("data is: " + arguments[0] + // <== junk               "\nnew token is: " + newtoken); // <== 1     }); alert(newtoken); // alerts "1" }); 

info on $.get()

note if update newtoken in get callback things can tricky due asynchronous nature of call. basically, aware of fact write in callback of $.get() executed when request done ( while later ), after $.get() within doc ready executed right away, , callback have access state of variables when doc ready function returned................ basically, can give newtoken initial value , work in callback, else might cause results don't except.

some examples:

$(document).ready(function(){     var newtoken = 1;      $.get("junk.php",         function() {             newtoken++;             alert(newtoken); // alerts 2, far good.         });     }); 

$(document).ready(function(){     var newtoken = 1;      $.get("junk.php",         function() {             newtoken++;             alert("get: " + newtoken); // alerts 3 - last alert         });      newtoken++;     alert("ready:" + newtoken); // alerts 2 -                                  // happens before server responds }); 

jsfiddle example


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -