How can I return a value from an AJAX request? [duplicate]

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_variable is undefined when it is returned.

Effectively, your code works as follows:

function sendRuest(someargums) {
     /* some code */

     var the_variable;

     /* some code */

     return the_variable;
}

var data = sendRequest(someargums);

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

function () {
  var theResult = sendRuest(args);

  // do something;
}

You should do:

function () {
  sendRuest(args, function (theResult) {
     // do something
  });
};

and modify sendRuest as follows:

function sendRuest(someargums, callback) {
     /* some code */

     //here's that other function 
     request.onreadystatechange =   
        function() {                
            if (request.readyState == 4) {    
                switch (request.status) {
                    case 200:
                        callback(request.responseXML);

        /* a lot of code */ 

        //somewhere here the function closes
        }
}

Leave a Comment