views:

85

answers:

4

Hello,

I am trying to execute a loop with a JSON query inside it. My code looks something like:

for (var i = 0; i < numitems; i++) {
   var currentitem = items[i];
   $.getJSON("http://localhost/items.php", {'itemname' : currentitem},
   function (json) {
      alert (json);
   });
}

But it seems like the for loop doesn't wait for the json query to finish and immediately goes on to the next one. Is it possible to implement a loop (doesn't have to be a for loop) that executes the current JSON query and proceeds to the next element in the array once a response has been received from json?

Thank you!

A: 

$.getJSON is an asynchronous call, meaning that it returns almost instantly but doesn't complete until some time later. That's why you pass it a callback---the callback (i.e. the function you pass in line 4) is what's executed when the AJAX request actually completes. The docs have some more details.

You'll want to rethink your strategy here: if you want these requests to be executed one-at-a-time, each needs to be called from the callback of the one before. Or you'll just have to deal with the asynchronous nature of the callbacks; it can be extremely useful.

kevingessner
+6  A: 
function nextItem(i)
{
  if(i < numitems)
  {
    var currentitem = items[i];
    $.getJSON("http://localhost/items.php", {'itemname' : currentitem},
      function (json) {
        alert (json);
        nextItem(i + 1);
      });
  }
}

nextItem(0);

Put this in the same place you currently have your for loop (don't move the function out).

Matthew Flaschen
Good old recursion. I will give this a try.. Seems like it should work perfectly.
Aamir Mansoor
A: 

getJSON is asynchronous. The loop will not wait for the JSON response.

Your code should still work, however your alert()s will be delayed.

If you want it to wait for the response you will need to make the callback function iterate through your list (my example probably wont work)

var items = [ "im", "not", "sure", "whats", "in", "here" ];

function bahJSON(index) {
   if (!index) index=0;
   var currentItem = items[index];
   $.getJSON("http://localhost/items.php", {"itemname": currentItem },
   function(json) { 
      alert(json);
      if (index<items.length) {
         bahJSON(index+1);
      }
   });
}
bahJSON();
NickSlash
+1  A: 

The following executes a JSON response after the previous JSON response has been completed:

function nextItem(i) {
var currentitem = items[i];
$.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "http://localhost/items.php",
        data: "{'itemname' : currentitem}",
        dataType: "json",
        complete: function() {
            if (i<numitems) {
                i++;
           nextItem(i);
        }

        },
        error: function(request, status, errorThrown) {
            alert(status);
        }
    });
}
Alison