I am making an AJAX request that updates the value of a variable (foo
) with a response from the server. Here is the code I am using:
At the point when you alert the value of foo
, the success handler has not yet fired. Since it is the success handler that reassigns the variable, its value remains an empty string.
The timeline of events looks something like this:
foo
is assigned the empty stringfoo
is alerted. (Note that foo
hasn't changed yet)foo = "New value:" + this.responseText;
Since we want to alert the value of foo
after it has changed, the solution is to put the alert in the success callback.
Now it will be executed after the AJAX response is received.