driesken
driesken

Reputation: 103

Wait for ajax requests in array to be completed

I'm trying to iterate through the ID's (containing an URL) of checked checkboxes. With each checkbox, it generates an AJAX-get which does a certain action on the database. This is working, however not all AJAX-gets seem to be executed (the redirect gets executed too fast).

As adviced, I've tried to make use of '$.when.apply', however, this doesn't seem to be working. I get a 'missing ) after argument list', most certainly generated in the part where I'm pushing the ajax-get.

Is this the right way or should I try another method?

$("#marksolved").click(function () {
    var ajaxrequests = [];

    // Loop through checkboxes.
    $('input:checked').each(function () {
        // Each id of a checkbox contains an URL.
        var markurl = $(this).attr('id');

        // Do the request.
        ajaxrequests.push($.ajax({
            method: 'GET',
            url: markurl,
            cache: false
        });
    });

    // Check if all requests have completed.
    $.when.apply($, ajaxrequests).then(function () {
        // All requests have completed. An ajax-redirect will eventually take place too fast...
        alert('All actions done!');

    });
});

Upvotes: 3

Views: 558

Answers (4)

xdumaine
xdumaine

Reputation: 10329

You can use $.ajaxStop() to have an event raised when all ajax requests have ended, or $.ajaxComplete() for when all requests have completed.

Upvotes: 1

Ozzy
Ozzy

Reputation: 8312

If you know how many ajax requests you are making, you could do something like this:

var ajax_count = 0;
var ajax_checker;
var ajax_n = 3;
$('input:checked').each(function() {
  ...
  ajaxrequests.push($.ajax({
    method:'GET',
    url: markurl,
    cache: false,
    success: function(){ ajax_count++; }
  });
}

// Check if all requests have completed.
function ajax_complete() {
  if (ajax_count >= ajax_n) {
    clearInterval(ajax_checker);
    //continue working
    alert('All actions done!');
  }
}

ajax_checker = setInterval(function() {ajax_complete();}, 50);

Upvotes: 0

Jason P
Jason P

Reputation: 27012

I get a 'missing ) after argument list', most certainly generated in the part where I'm pushing the ajax-get.

    ajaxrequests.push($.ajax({
        method: 'GET',
        url: markurl,
        cache: false
    });

should be:

    ajaxrequests.push($.ajax({
        method: 'GET',
        url: markurl,
        cache: false
    }));

It's missing a ), like the error says.

Side note: It would probably be far more efficient to combine all of your requests into one batch request instead of having one request for each checkbox.

Upvotes: 2

Rômulo Spier
Rômulo Spier

Reputation: 231

try setting the ajax async option to false

$.ajax({
    method:'GET',
    url: markurl,
    cache:false,
    async: false
});

Upvotes: 0

Related Questions