Thursday, 1 February 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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...