I\'m trying to call a function that contains jQuery code. I want this function to return the results of the jQuery statement. It is not working, and I\'m trying to figure ou
An efficient way is to use jQuery's Deferred method, both sync/async requests to server and wait for deferred.resolve() and then return the deferred promise object. Looks a bit tedious, but a little study is sure helpful for large data. ( tvanfosson's function works well in this case, but when I was working on google analytics data, a large amount of information made me crazy and thus i need to find this solution)
function showResults(name) {
var deferred = $.Deferred, requests = [];
requests.push($.ajax({url:"/path/to/uri/?name=" + name, type: "GET", async: false}).done(function(d) {
//alert or process the results as you wish
}));
$.when.apply(undefined, requests).then(function() { deferred.resolve(); });
return deferred.promise();
}
the returned promise object can also be used with $.when(showResults('benjamin')).done(function() { }); for post modifications (like chart/graph settings etc). totally reusable.
You may also put this function in a loop of $.deferred requests like,
function updateResults() {
var deferred = $.Deferred, requests = [];
requests.push($.ajax(url:"/path/to/names/?nameArr=" + jsonArrOfNames, type: "GET", async: false}).done(function(res) { requests.push(showResults(res[0]));}) );
$.when.apply($, requests).then(function() { deferred.resolve(); });
return deferred.promise();
}