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 ?
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; } } }); });
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.
Cut and paste whatever code you need to execute in the callback function passed to success . Some good answer is already provided.
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
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) })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With