Thursday, February 1, 2018

javascript - Ajax call not returning correct variable

Ajax is asynchronous. So the execution continues without waiting for the return value. You could 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;
};


Code the handling method to process the total:



var processReturn = function(total) {

//use the total value here
console.log(total);
};


That should take care of it.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...