AJAX response data not saved globally?

My question is that my lines below do not save this variable in the global scope:

var somedata; $.ajax({ cache: false, url: verification_url, success: function(data){ somedata = data; } }); alert(somedata); // Undefined 

What am I doing wrong? Does it need to be wrapped in a separate function or what?

+4
source share
2 answers

The alert() code is run before receiving a response from $.ajax .

That is why it is 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 warnings are out of order. By default, an AJAX request does not prevent the execution of subsequent code.

This is the whole purpose of having a callback method. This is a method called at the appropriate time, rather than relying on synchronous execution.

+11
source

AJAX is asynchronous. What A stands for Abbreviation. You can access 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. 

Thus, any code that needs to process the results must be placed in a success callback or in a function that is called from the success callback. You should not rely on global state for this template.

+5
source

All Articles