Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Json inside loop

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!

like image 353
Aamir Mansoor Avatar asked Nov 25 '25 18:11

Aamir Mansoor


1 Answers

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).

like image 52
Matthew Flaschen Avatar answered Nov 28 '25 08:11

Matthew Flaschen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!