I am having the issue of my below shown lines not storing the variable into the global scope:
var somedata;
$.ajax({
cache: false,
url: verification_url,
success: function(data){
somedata = data;
}
});
alert(somedata); // Undefined
What am I doing wrong? Do I need to wrap this into a separate function or what?
The alert()
code runs before the response from $.ajax
is received.
That's why it's undefined
.
var somedata;
$.ajax({
cache: false,
url: verification_url,
success: function(data){
somedata = data;
alert( somedata ); // 2. this will occur after the response is received
}
});
alert(somedata); // 1. this will occur first
Here you can see that the alerts happen out of order. By default an AJAX request does not prevent subsequent code from running.
That's the entire purpose of having a callback method. It is a method that gets called at the appropriate time, instead of relying on synchronous execution.
AJAX is asynchronous. That's what the A
stands for in the acronym. You can access the results only in the success callback:
$.ajax({
cache: false,
url: verification_url,
success: function(data){
// HERE AND ONLY HERE YOU HAVE THE RESULTS
// So it is here that you should manipulate them
alert(data);
}
});
// this line is executed MUCH BEFORE the success callback
// and the server hasn't yet sent any response.
So any code that needs to manipulate the results must be place inside the success callback or in a function which is invoked from the success callback. You should not be relying on global state for this pattern.