Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait until jQuery ajax request finishes in a loop?

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 ?

like image 493
tcj Avatar asked Nov 29 '13 18:11

tcj


People also ask

How do I make jQuery wait for an ajax call to finish before it returns?

ajax({ url: $(this). attr('href'), type: 'GET', async: false, cache: false, timeout: 30000, fail: function(){ return true; }, done: function(msg){ if (parseFloat(msg)){ return false; } else { return true; } } }); });

Is there a way to limit the time an ajax call will run?

As for limiting the number of AJAX calls per domain (either concurrent outstanding calls, or total calls made, or any other metric you might be interested in), the solution would be the venerable CS classic: add another layer of abstraction.

Is there any way to wait for ajax response and halt execution?

Cut and paste whatever code you need to execute in the callback function passed to success . Some good answer is already provided.


2 Answers

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

like image 173
charlietfl Avatar answered Sep 29 '22 16:09

charlietfl


For jQuery 3.x+ and modern browser that support native Promise, Promise.all could be used this way:

var promises = []; for (var i = 0; i < $total_files; i++) {    // jQuery returns a prom     promises.push($.ajax({       /* your ajax config*/    })) }  Promise.all(promises) .then(responseList => {    console.dir(responseList) }) 

If your files are already stored in a list then you could use map instead of a loop.

var fileList = [/*... list of files ...*/];  Promise.all(fileList.map(file => $.ajax({       /* your ajax config*/ }))) .then(responseList => {    console.dir(responseList) }) 
like image 26
t.niese Avatar answered Sep 29 '22 16:09

t.niese