Reputation: 2018
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.
Upvotes: 1
Views: 5027
Reputation: 8198
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;
}
Upvotes: 7