Ok. I'm totally baffled. Here's the code:
$(document).ready(function(){
var newToken = 1;
$.get("junk.php",
function(newToken) {
alert(newToken); // alerts "junk"
});
alert(newToken); // alerts "1"
});
As per my comments, the first alert of newToken is "junk" (the only output of junk.php). Once outside the .get, newToken reverts to "1". I need to get this variable set to the output from junk.php. Is this not possible? I've tried everything, and searched everywhere.
Thanks.
You're shadowing the first
newToken
variable with a newnewToken
variable that is used as an argument:Problem:
Work around... use different names, or even the
arguments
array:Solution:
Info on $.get()
Note that if you update
newToken
in theget
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 givenewToken
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:
jsFiddle example
I found the answer - of all places on the jQuery website (surprise, surprise), buried in the commentary.
This solves the problem - being that it was asynchronous, and that needed to be set to false. This cannot be accomplished using the jQuery.get(), but must be jquery.ajax, where the async:false can be set.
With the request in this format, newToken can be used throughout the script. Hope this ends up helping someone else.
First, your definition of
newToken
is inside the context of that anonymous function passed to$(document).ready()
, so it's not global at all. I don't think this is the problem real, though...More serious is this: The call to
$.get
is asynchronous, so control passes immediately to youralert(newToken)
statement without waiting for the http request to finish, or for its callback to run. So any code relying on data retrieved in that call should run in its callback.