You're shadowing the first newToken
variable with a new newToken
variable that is used as an argument:
Problem:
$(document).ready(function(){
var newToken = 1; // <== newToken number 1
$.get("junk.php",
function(newToken) { // <== This is newToken number 2.
// since it's the first argument
// in the get success function it will
// be the data returned.
alert(newToken); // <== Alerts the data returned. newToken number 1 is
// shadowed, obscured, covered up...
});
alert(newToken);
});
Work around... use different names, or even the arguments
array:
Solution:
$(document).ready(function(){
var newToken = 1;
$.get("junk.php",
function() { // <== don't shade newToken
// you could use another variable name like "data"
// but I decided to use the arguments array for kicks
alert("Data is: " + arguments[0] + // <== junk
"\nNew Token is: " + newToken); // <== 1
});
alert(newToken); // alerts "1"
});
Info on $.get()
Note that if you update newToken
in the get
callback things can get tricky due to the asynchronous nature of the call. Basically, be aware of the fact that everything you write in the callback of $.get()
will get executed only when the request is done ( a while later ), but everything after $.get()
but within the doc ready will get executed right away, and the get callback will have access to the state of variables as they were when the doc ready function returned................ basically, you can give newToken
an initial value and then work with it in the get callback, but anything else might cause results that you don't except.
Some examples:
$(document).ready(function(){
var newToken = 1;
$.get("junk.php",
function() {
newToken++;
alert(newToken); // alerts 2, so far so good.
});
});
$(document).ready(function(){
var newToken = 1;
$.get("junk.php",
function() {
newToken++;
alert("get: " + newToken); // alerts 3 - this is the last alert
});
newToken++;
alert("ready:" + newToken); // alerts 2 -
// this happens before the server responds
});