Click here to Skip to main content
15,896,269 members
Articles / Programming Languages / Javascript
Tip/Trick

Repeated Ajax Call

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
24 Dec 2013CPOL1 min read 11.8K   2  
How to make a sequential Ajax call

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:  

 

JavaScript
    function GetAllCitiesGeocodes() { 

            function GetCityGeoCode(ctList) {

                if (currentIndex == ctList.length) {

                    OnAllGeocodeDataReady(); //jump out of the call.

                    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++; //Increase the index to point to the next city


                        //Recursive for next call

                        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: 

JavaScript
$.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.  

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) TrafficTech Inc.
Canada Canada
I am Sitang Ruan, a .Net developer focus on web application development for 6 years. I like to write elegant and efficient codes to provide user a smooth and solid experience. I also like to take very complicated and challenging tasks.

Comments and Discussions

 
-- There are no messages in this forum --