you must remove the async: false
. which in turn allows the requests to complete and be appended as they finish. However, you'll then realize that they are being appended out of order! to fix that, we can use promise objects and .then.
images = 10;
var req = $.ajax({
type: "POST",
url: "processimage.php",
data: {
image: images
},
success: function (data) {
$("#logger").append(data + '<br />');
}
});
images--;
while (images > 0) {
req.then(function(){
return $.ajax({
type: "POST",
url: "processimage.php",
data: {
image: 1
},
success: function (data) {
$("#logger").append(data + '<br />');
}
});
});
images--;
}
Now, there's still one more possible issue. if you needed to pass the current value of images
with each request, the previous code will send all requests after the first with the last value of images
. To fix that, we can use an iffe.
images = 10;
var req = $.ajax({
type: "POST",
url: "processimage.php",
data: {
image: 1
},
success: function (data) {
$("#logger").append(data + '<br />');
}
});
images--;
while (images > 0) {
(function(i){
req.then(function(){
return $.ajax({
type: "POST",
url: "processimage.php",
data: {
image: i
},
success: function (data) {
$("#logger").append(data + '<br />');
}
});
});
})(images);
images--;
}
And then you can make it DRYer as suggested below by storing the options in a separate variable:
images = 10;
var ajaxOpts = {
type: "POST",
url: "processimage.php",
data: {
image: 1
},
success: function (data) {
$("#logger").append(data + '<br />');
}
};
var req = $.ajax(ajaxOpts);
images--;
while (images > 0) {
(function(i){
req.then(function(){
ajaxOpts.data.image = i;
return $.ajax(ajaxOpts);
});
})(images);
images--;
}