views:

170

answers:

2

How to check if an ajax function is busy from a previous call? How can i prevent the call to an ajax function if it's readyState != 4 yet from a previous call?

+4  A: 

You can use a boolean and an appropriate onreadystatechange functoin;

var inprogress = true;
ajaxRequest = ...
ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
     inprogress = false;
    }
}
Matthew Flaschen
A: 

The question is if you want to skip the Ajax call if the previous call is still busy or not? If you want to skip it the solution is easy and the one of Matthew perfectly suits your need. However if you want to start executing the call after the previous one is finished, that's a whole different story. I can provide you with some code if needed.

Have been working on a solution:

<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"&gt;&lt;/script&gt;
<script language="javascript" type="text/javascript">
var requestInProcess = false;
var timer = null;

function requestSomeStuffA() {
 var responseHolder = $("responseHolder");

 new Ajax.Request(
     "http://webservicelocation/",
     {
         method: 'GET',
         contentType: 'application/json; charset=utf-8',
         onCreate: function() { 
          requestInProcess = true;
         },
         onSuccess: function(transport) {
             //do something with the transport
         },
         onFailure: function(error) {
             //throw a nice exception
         },
         onComplete: function() {
             requestInProcess = false;
         }
     }
 );
}

function requestSomeStuffB() {
 clearTimeout(timer);

 if(requestInProcess) {
  //wait again for a while
  timer = window.setTimeout("requestSomeStuffB()", 10); //timeout in miliseconds
 }
 else{
  //execute the next Ajax request
 }
}
</script>

When you call first requestSomeStuffA and then requestSomeStuffB, requestSomeStuffB will wait for requestSomeStuffA to be finished. Hope this is useful for you.

Joop