I've got a custom function, which calls ajax request and I'm able to save response data to variable and return it. 0 is always returned, but alert shows e.g. 3712.
Here is the function:
function getNo(index, val) {
var $ret = 0;
$('body').showLoading();
$.ajax({
type: 'POST',
url: BASE_URL + 'tools/no.php?id='+index+'&value='+val,
data: $("#form").serialize(),
cache: false,
success: function(data) {
$('body').hideLoading();
alert('data: ' + data);
$ret = data;
}
});
return $ret;
}
-
possible duplicate of return from a function ajax and JavaScript asynchronous return value / assignment with jQuery and lots of others...Felix Kling– Felix Kling2011年11月10日 09:43:38 +00:00Commented Nov 10, 2011 at 9:43
3 Answers 3
because ajax is asynchronous, when return $ret; is executed, the response is not ready yet, so its initial value 0 is returned.
you have to do what you want to do in the success callback function rather than return.
5 Comments
async: false often hangs the browser till the server responseThis will return ZERO because of the asynchronous call. Rather I would suggest you to pass a callback method to work with the response.
See an example below:
function getNo(index, val, callback) {
var $ret = 0;
$('body').showLoading();
$.ajax({
type: 'POST',
url: BASE_URL + 'tools/no.php?id=' + index + '&value=' + val,
data: $("#form").serialize(),
cache: false,
success: function (data) {
$('body').hideLoading();
callback(data);
}
});
return $ret;
}
//USAGE
getNo(3, "value", function (data) {
//do something with data responded from the server
alert(data);
});
1 Comment
Because "A" in Ajax stands for Asynchronous, return $ret; is executed before the Ajax call finds it's way back to success function.
Rather than trying to return the value, try to call a function within the ajax success block.
success: function(data) {
$('body').hideLoading();
alert('data: ' + data);
$ret = data;
doSomething(data);
}