tags:

views:

468

answers:

2

I'm probably missing something obvious, but I don't seem to be able to get my AJAX posts to run consecutively instead of concurrently with jQuery.

ad_numbers is an array of numeric IDs.

$(ad_numbers).each(function() {
  ad_number = $.trim(this);

  if(!ad_number) { return true; }

  $.post('/fetch.php', { ad_number: ad_number }, function(data, textStatus) {
    $('#log').prepend('<p>' + data + '</p>');
  });
});

In fetch.php, I've had it sleep(2) so I can make sure it works correctly. Instead of waiting for the first POST to go through before stepping on to the next ad number in the array, it seems to be running all of them at once concurrently.

I'm guessing $.post() is returning before it completes? What's the best way to avoid this?

+6  A: 

Try adding async: false to your options.

$(ad_numbers).each(function() {
    ad_number = $.trim(this);

    if(!ad_number) { return true; }

    $.ajax({
        type: 'POST',
        url: '/fetch.php',
        data: {ad_number: ad_number},
        async: false,
        success: function(data, textStatus) {
            $('#log').prepend('<p>' + data + '</p>');
        }
    });
});
Paolo Bergantino
Thank you very much. :-)
ceejayoz
+2  A: 

Ajax is asynchronous. fetch.php may be calling sleep, but the javascript works in an asycronous pattern, and doesnt wait for your sleep to end.

Mike_G