Search This Blog

Put limit on number of AJAX calls using JavaScript


Problem:
When working with AJAX using javaScript, (ASP .Net), there is one common problem. i.e. Multiple server calls, which may lead to undesirable results.


Solution:
There are many mechanisms/codes/ways to stop multiple calls to the server, one of them is 'stack connections technique'… (This name is given by me just now :)    )

Whenever there is an AJAX call through javaScript, there are two options: (1) Sync Call, (2) ASync Call    [You can read more about AJAX, Sync & ASync calls at: http://www.code4coder.com/2010/01/ajax-net.html ]

  1. When there is Sync Call:
    1. There is no need to do anything, as user cannot do anything, until server response backs.

  2. When there is ASync Call:    (JavaScript code)

    1. Declare a constant
      var maxAjaxCallAllowed=2;    //2 ajax calls are allowed.

    2. Declare an array (stack) to keep track of AJAX calls:
      var openAjaxCalls = new Array();

    3. Whenever sending ASync request; always check
      If (openAjaxCalls.length < maxAjaxCallAllowed){
      openAjaxCalls.push(1);    //any value, not 1 has not significance, other than that it is creating a new item in stack/array.
      ClassName.Ajax_Method(All_Parameters_Passed, Ajax_Callback_Method);    //Give call to server side method.
      }
      else{
      alert('Server call not possible at this time);
      }

    4. In Ajax call back method
      function Ajax_Callback_Method(xmlResponse){
      openAjaxCalls.pop();
      // perform operation on xmlResponse object.
      }

http://code4coder.com