Tuesday, 27 August 2013

Wait for ajax requests in array to be completed

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!');
});
});

No comments:

Post a Comment