2

I need to return the data from an nested ajax call but also need the ajax call to stay asynchronous.

I found some related questions but can't get it to work in the situation below. I assume returnData is being returned before the ajax call is done, but I can't find an solution.

function makeRequest(command, postData){

    var returnData;

    $.ajax({

        url: 'call.php?command='+command,
        data: postData,
        type: 'POST'

    }).done(function(data){
        returnData = data;
    });

    return returnData;
}
2
  • put the return inside the .done callback. Commented Apr 17, 2012 at 10:23
  • @Aidanc — which will return the data to … where? Commented Apr 17, 2012 at 10:25

3 Answers 3

4

Yes since this call is async returnData is returned immediately. If you need to use returndata pass it to a function in the callback

function makeRequest(command, postData, functionToCallAfterAjax){

    var returnData;

    $.ajax({

        url: 'call.php?command='+command,
        data: postData,
        type: 'POST'

    }).done(function(data){
        functionToCallAfterAjax(data);
    });


}

Of course you could pass the function to call as a parameter.

This means that if your code was meant to do:

var returnedData = makeRequest(command, postData);
anotherFunction(returnedData);

you should do simply (using the code above)

makeRequest(command, postData, anotherFunction);

and everything will work

Sign up to request clarification or add additional context in comments.

Comments

0

You can't. Asynchronous events don't work like that.

The HTTP request is sent, then the function that triggers it continues immediately. The callback won't be fired until the HTTP response has arrived, but which time the calling function will have ended.

You must have your callback (the function you are passing to done()) perform whatever further processing is needed.

Comments

0

You're returning the value of returnData before the .done() function has run. Correct your code by passing the received data to a function for processing:

function makeRequest(command, postData){
    $.ajax({
        url: 'call.php?command='+command,
        data: postData,
        type: 'POST'
    }).done(function(data){
        HandleCallBack(data);
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.