$getJSON and for loop issue

That’s a classical problem : i has the value of end of loop when the callback is called.

You can fix it like this :

for (var i = 0; i < array.length; i++) {
    (function(i) { // protects i in an immediately called function
      $.getJSON('/api.php?action=query&list=querypage&qppage=" + array[i] + "&format=json', function (data) {
        $('#' + array[i]).text(data.query.querypage.results.length);
      });
    })(i);
}

2018 addendum:

There’s now another cleaner solution in today’s browsers: use let instead of var:

for (let i = 0; i < array.length; i++) {
    $.getJSON('/api.php?action=query&list=querypage&qppage=" + array[i] + "&format=json', function (data) {
        $('#' + array[i]).text(data.query.querypage.results.length);
    });
}

Leave a Comment