Reputation: 841
I have the following code:
for (i=1;i<=pages;i++) {
$('#procout').append(Processing Page#"+i+"<br />");
$.ajax({
url: 'processor.php',
data: {storen: perpage, pagen : i},
success: function(data) {
$('#procout').append(data+"<br />");
}
});
}
What I am trying to do is make the script wait for the Ajax response after every loop. Instead it prints out the "Processing Pages" lines all together and the the Ajax responses from each run in the order the server responds (out of order). I tried setting the async option to false, but that simply causes the JS to wait until all six requests are done and then output everything from all runs together.
Note: The values of the pages, perpage, and pagen are irrelevant to the issue.
Upvotes: 2
Views: 2947
Reputation: 83376
Since you've already tried making the ajax requests async:false
(which is seldom if ever a good idea anyway), consider breaking your loop body into a function that makes the ajax request, and then runs the next request in the callback:
function runRequest(num){
if (num > pages) return; //since your original was looping while i <= pages
$('#procout').append("Processing Page#" + num + "<br />");
$.ajax({
url: 'processor.php',
data: {storen: perpage, pagen : num},
success: function(data) {
$('#procout').append(data + "<br />");
runRequest(num + 1);
}
});
}
And then of course starting the process off with
runRequest(0);
Upvotes: 4