I have a function which declares a variable with the var keyword. It then launches an AJAX request to set the value of the variable, and this variable is then returned from the function.
However, my implementation fails and I ‘don’t know why.
Here’s a simplified version of the code;
function sendRequest(someargums) {
/* some code */
var the_variable;
/* some code */
request.onreadystatechange =
//here's that other function
function() {
if (request.readyState == 4) {
switch (request.status) {
case 200:
//here the variable should be changed
the_variable = request.responseXML;
/* a lot of code */
//somewhere here the function closes
}
return the_variable;
}
var data = sendRequest(someargums); //and trying to read the data I get the undefined value
AJAX requests are asynchronous. Your sendRuest function is being exectued, the AJAX request is being made but it happens asynchronously; so the remainder of sendRuest is executed, before the AJAX request (and your onreadystatechange handler) is executed, so
the_variableis undefined when it is returned.Effectively, your code works as follows:
And then some time later, your AJAX request is completing; but it’s already too late
You need to use something called a callback:
Where you previously may have had
You should do:
and modify
sendRuestas follows: