How to wait until jQuery ajax request finishes in a loop?
ajax, javascript, jquery
Solution
You can create an array of promises so that once all promises are resolved you can run your `all done` code.
var promises = [];
for (var i = 0; i < $total_files; i++){
/* $.ajax returns a promise*/
var request = $.ajax({
/* your ajax config*/
})
promises.push( request);
}
$.when.apply(null, promises).done(function(){
alert('All done')
})
DEMO
Problem
I have that code : ``` for (var i = 0; i < $total_files; i++) { $.ajax({ type: 'POST', url: 'uploading.php', context: $(this), dataType: 'json', cache: false, contentType: false, processData: false, data: data_string, success: function(datas) { //does something }, error: function(e) { alert('error, try again'); } }); } ``` It uploads images very well but the problem is that I can't find a way to upload the images one by one, I tried to put the option async to false but it freezes the web browser until all images are uploaded which is not what I want, I want to emulate somehow this "async : false" option to perform the same thing but without freezing the web browser. How to do this ?