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!
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With