I have a number of checkboxes and if a checkbox is checked I am sending its value with .ajax.
At the moment I am using async : false
to make sure it loops from the next after the ajax success.
However, it kind of freezes the browser until it completes .each
loop.
I saw something similar done here: jQuery continue loop execution after ajax success but can't figure out how to adapt it to my case where I am using .each
instead of for
$("input:checkbox:checked").each(function () {
$.ajax({
async : false,
url:"import.php",
method:"POST",
data:{id:id, val:val},
success:function(data) {
//do some action
}
});
});
CodePudding user response:
Using the same principle from https://stackoverflow.com/a/7330753/378779:
var elements = $("input:checkbox:checked")
var i = 0;
doLoop();
function doLoop() {
if ( i >= elements.length ) {
return;
}
// To get the element we are up to: $(elements[i])
$.ajax({
async : false,
url:"import.php",
method:"POST",
data:{id:id, val:val},
success:function(data) {
//do some action
i
doLoop()
}
});
}
Presumably you'll want to change data:{id:id, val:val}
to use the id and value from the individual checkbox, so before the .ajax()
call you will probably want to:
let e = $(elements[i])
And to get the id and value:
data:{id:e.attr('id'), val:e.val()}