Ajax call does not return correct variable
Possible duplicate:
jQuery: return data after successful ajax success
I am having a problem getting this ajax function to work and not sure where I am confused.
var getTotalEntries = function(query) {
var total;
$.ajax({
url: url,
data: query,
dataType: 'jsonp',
success: function(data) {
console.log(data.total);
total = data.total;
}
});
return total;
};
this log 65 to the console but returns undefined ... not sure what is going on.
+3
source to share
2 answers
The Ajax call and return statement are both asynchronous, not synchronous, so the return statement is triggered before the ajax call returns and sets the variable.
One way to work around this problem is to do whatever action you want to take with the data inside the success callback.
$.ajax({
url: url,
data: query,
dataType: 'jsonp',
success: function(data) {
console.log(data.total);
total = data.total;
// do stuff with total here, or invoke function that uses total
doSomething(total);
}
});
+5
source to share
Ajax is asynchronous. Thus, execution continues without waiting for the return value. You can do something like this:
var getTotalEntries = function(query) {
var total;
$.ajax({
url: url,
data: query,
dataType: 'jsonp',
success: function(data) {
console.log(data.total);
total = data.total;
//pass the total value here
processReturn(total);
},
//you may want to add a error block
error: function(e, xhr, settings, exception){
}
});
return total;
};
Enter the processing code to process everything:
var processReturn = function(total) {
//use the total value here
console.log(total);
};
This should take care of this.
+1
source to share