I want to run ajax in every loop of the selected checkbox. However ‘jquery each’ ignores the ajax process. Completed or not completed the loop will continue. Sorry for my language, hope it’s understandable.
Here is an example of the code I made.
$('input[name="options[]"]:checked').each(function() {
jQuery.ajax({
url: "www.example.com",
type: "POST",
data: {
name:name
},
success: function(data) {
// do something
}
});
});
I have tried using async:false in the ajax option, but the page freezes, and will return to normal after the process is complete.
2
Answers
So all you have to do with any kind of Promise batches is gather all of them to array and pass to "batch Promises" function. No matter if it’s jQuery, Angular or other
Here is an alternative solution using
fetch()
, as it is available in all modern browsers (no jQuery needed):In this sample script I collect the responses from three Ajax calls to the publicly avaible resource provided by typicode.com: The resulting array then consists of three arrays containing the users, posts and comments. In my demo I simply provide
console.log
as the processing function. This will of course be different in a real life situation.fetch
can be used withPOST
too, see here for more details: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch .