I have an $.each()
loop, looping through some selected checkboxes and calling an ajax call for each of the checkboxes. Obviously, $.each()
doesn't wait on the ajax. I could put ajax:false on the ajax call, but due to deprecation warnings, I'd rather not.
Therefore, I'm trying to use $.Deferred()
, but the each iteration doesn't appear to be waiting on it either.
Here's the code:
.each($checkboxes, function(key, checkbox) {
$def = $.Deferred();
$checkbox = $(checkbox);
$.ajax({
'url': 'ajax/myajaxcall.php',
'data': {
id: $checkbox.data('id')
}
}).complete(function() {
console.log('done');
$def.resolve('done');
});
return $def.promise();
});
ACTUAL SOLUTION
I'm fully aware of how to use ajax, however the above code had gone through a number of refactors and trials of different ways to do things to try to get the result I wanted.
What i've decided to do is drop the $.each() and manually interate through the checkboxes by calling a function which, when completed recalls itself with an incremented key for the checkboxes.
This solution 100% ensures that the ajax calls are being ran one-by-one.
var $checkboxes = $('input[name="mycheckboxes"]:checked'),
checkboxKey = 0,
checkboxLength = $checkboxes.length;
function callAjax(key) {
console.log(key);
$checkbox = $($checkboxes[key]);
console.log('call ajax');
console.log($checkbox);
$.ajax({
'url': 'ajax/myajaxcall.php',
'data': {
'id': $checkbox.data('id')
}
}).complete(function() {
console.log('done');
if(key < checkboxLength-1) {
key += 1;
createInvoice(key);
}
else {
console.log('complete');
}
});
}
if(checkboxLength > 0) {
callAjax(checkboxKey);
}