w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Wait for multiple getJSON calls to finish

This is easy if you use jQuery's deferreds. There is a method, $.when, that waits for multiple promises to complete then runs a callback. That's what you should use here.

Don't use a global obj variable, you can just use the returns from the AJAX calls.

function getData(id) {
    var thisI = i;
    var url = "www.whatever.com?id=" + id;
    return $.getJSON(url);  // this returns a "promise"

So, instead of populating obj, we just return the promise. Then in your loop, you collect all of them.

var AJAX = [];
for (i=0; i < ids.length; i++) {

Then we need to hook up the callback when all of them are done:

$.when.apply($, AJAX).done(function(){
    // This callback will be called with multiple arguments,
    // one for each AJAX call
    // Each argument is an array with the following structure: [data,
statusText, jqXHR]

    // Let's map the arguments into an object, for ease of use
    var obj = [];
    for(var i = 0, len = arguments.length; i < len; i++){

    document.getElementById("txt").innerHTML = obj[0]['field'];

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.