I’m making multiple AJAX requests inside a loop. Here’s my code for that:
// set defaults
var app_id = 'xxx';
var secret = 'yyy';
var auth_token = 'zzz';
// list of items to call in the API
var insights_to_check = ['application_permission_views_top_unique', 'application_installation_adds_unique', 'application_installation_removes_unique'];
var json_responses = {};
var ajax_calls = [];
// construct the API url
for (var i in insights_to_check) {
var insight = insights_to_check[i];
var url = 'https://graph.facebook.com/' + app_id + '/insights/' + insight + '?' + auth_token;
ajax_calls.push(get_json(url, insight));
}
// when all ajax requests are done, call the process function
$.when.apply($, ajax_calls).done(function(){
process_json(json_responses);
});
// collect responses to the ajax request in a global object
function get_json(url, insight) {
$.getJSON(url, function(json) {
json_responses[insight] = json;
});
}
// show the global object
function process_json(all_json) {
console.log(all_json);
}
The code has a weird problem: the first time it runs, I can see the AJAX requests firing and returning, but when process_json() gets called, it logs undefined. If I manually invoke it a second time, it returns the json as expected.
It seems that my deferred callback is firing before the AJAX requests are complete, or at least. before they’ve been able to assign their response to the global json_responses object. Can anyone see anything glaringly obvious here?
I’m not sure why it logs
undefined(it does not for me if I omit the Ajax calls) but one problem with your code is that the.done()callback is executed immediately asajax_callsis an empty array.You have to return the return value of
$.getJSONfromget_json:That might solve the issue.