There are two basic ways to do this:
Use promises to chain multiple ajax calls together. The chaining process will force sequential operation so one finishes and then the next one launches.
In the success handler of the ajax call, launch the next ajax call (your third option).
If the different ajax calls do not actually depend upon one another, you can also launch them all in parallel and then serialize just the results. This results in much faster end-to-end time.
Or, as others have suggested, if you can modify your web service so that multiple requests can be passed in one ajax call, then you can request all the data with one ajax call and the server will return all the data at once.
For the first option, here's an example of serializing ajax calls using promises:
Sequential function calls in javascript
// serialize all requests
function A() {
var p = $.get(url).then(function(data) {return $.post(url)});
for (var i = 1; i < 5; i++) {
// chain four more pairs of requests onto the original promise
p = p.then(function() {return $.get(url)})
.then(function(data) {return $.post(url)});
}
// return the promise so callers can monitor when A() is done
return p;
}
function B() {
// sequence these three operations one after the other
return ($.get(url)
.then(function(data) {return $.post(url + x)})
.then(update_dropdown)
);
}
// run them both, one after the other
A().then(B);
For the second option, you can't use a for
loop because (as you've already figured out, it just launches all the ajax calls at once). Instead, you restructure the looping so you launch the next iteration from the success handler. Here's an example of the second option taken from some other code I have lying around:
(function() {
var checked = $('.check_box_ping:checked');
var index = 0;
function next() {
if (index < checked.length ) {
var item = checked.eq(index++);
// use item here for your post
$.post({...}, function(response) {
// do your normal handling of the response here
...
// now kick off the next iteration of the loop
next();
});
}
}
next();
})();
Here are a couple other examples:
behavior of ajax call inside a for loop
Wait for AJAX to finish before proceeding with the loop?
While loop with jQuery async AJAX calls