1

I've got this code:

function someFunction(something1, something2) {

    $.post("execute.php", { someData1: something1, someData2: something2 }, function(data) {

        returnData = data;

    });

    return returnData;

}

Post function returns either false or true and I want this someFunction send this information further by return value, but it doesn't work. I'm guessing this return value returns before it posts so there's undefined, but I have no idea what to do about it.

emil.c
  • 1,987
  • 2
  • 26
  • 46
  • 1
    I suppose a reference to some good answer about asynchronous nature of AJAX requests should be added to the jquery faq http://stackoverflow.com/tags/jquery/info – zerkms Feb 13 '12 at 23:00

1 Answers1

7

The ajax call is asynchronous, meaning it runs 'out of the way'. The function is executed and returned immediately and javascript continues on its merry way, while the ajax call is executed 'out of the way'.

That is why it is returning undefined, because it isn't.

To prevent this behavior you need to set it to 'synchronous'. And you need to define returnData outside the scope of the function.

You can either do this by setting

$.ajaxSetup({async:false});

And then calling $.post,

Or you can do $.ajax(... {async:false}...);

So using the first method:

function someFunction(something1, something2) {
    $.ajaxSetup({async:false});  //execute synchronously

    var returnData = null;  //define returnData outside the scope of the callback function

    $.post("execute.php", { someData1: something1, someData2: something2 }, function(data) {

        returnData = data;

    });

    $.ajaxSetup({async:true});  //return to default setting

    return returnData;

}
Vigrond
  • 8,148
  • 4
  • 28
  • 46