Introduction
In some of cases, I may need to do repeated Ajax call in a strict sequential order, either to fetch some data or to save some data to DB. Ajax is nothing new however I must ensure each call is raised only after the previous call and its call-back has been completed, Otherwise, it is easy to see such a case: all the Ajax calls have been raised however the page is still waiting for the call-back of first call.
Solution
I find one good solution with a recursive mode.
1) Put your Ajax call codes into a function, say named as "RepeatCall", in the call-back codes call the function "RepeatCall" again (recursive).
2) Define a global index variable, say named as "CurrentIndex" to indicate the current index of the calls list
3) In the beginning part of function "RepeatCall", check the global variable "CurrentIndex". If it reaches to the count of total calls, then jump out the function
Codes
Download the attached demo project, you can see it is doing a repeated Ajax calls to Google geo-code service to fetch geo-codes for a bunch of cities. The main part of the codes are functions below:
function GetAllCitiesGeocodes() {
function GetCityGeoCode(ctList) {
if (currentIndex == ctList.length) {
OnAllGeocodeDataReady();
return;
}
geocoder.geocode({ 'address': ctList[currentIndex] }, function OnReceiveGeocodeFromGoogle(results, status) {
if (status = google.maps.GeocoderStatus.OK) {
geocodeList.push(results[0].geometry.location.lat() + "-" + results[0].geometry.location.lng());
currentIndex++;
GetCityGeoCode(ctList);
}
});
}
var currentIndex = 0;
GetCityGeoCode(cityList);
}
function OnAllGeocodeDataReady() {
$("#GeoCodeList").text(geocodeList.join(", "));
}
Others
Other than the mode discussed above, for some simple case, you can always make an "synchronous" Ajax call (with jQuery) to force the codes to wait for the result from server and then to continue your other stuff. Like below:
$.ajax({ async: false,
Conclusion
The delay between Ajax call and call back is the thing that makes the repeated Ajax call tricky and different from regular looping codes. That's why it is better to raise the next call inside the call-back of the previous one.