Snippets: Synchronous AJAX

Filed: Wed, Mar 28 2007 under Programming|| Tags: ajax synchronous javascript post get

For almost every situation under the sun, moon, and stars above you will want to use Asynchronous Ajax -- that is just a given. There are, however, some situations where Synchronous Ajax is mandatory, so it can be worthwhile getting a basic handle on how this technology works.

Asynchronous AJAX

Asynchronous AJAX will initiate a request for a file and then return control to the browser until, at some undetermined point in the future, the server finishes transmitting the request to the browser. If anything goes wrong in the request and/or transfer of the file, your program still has the ability to recognize the problem and recover from it.

Synchronous AJAX (SJAX)

Synchronous AJAX (Really SJAX -- Synchronous Javascript and XML) is modal which means that javascript will stop processing your program until a result has been obtained from the server. While the request is processing, the browser is effectively frozen. The browser treats the call like an alert box or a prompt box only it doesn't wait for input from the user, but on input by the remote server. 99.99% of the time the the response is quick and fast enough so that there isn't any problems. If anything goes wrong in the request and/or the transfer of the file, however, the user's browser may freeze for over two minutes until the request times out.

The advantages of using synchronous AJAX calls are that they are incredibly simple to code and you can use them in onunload and onbeforeunload events. An asynchronous AJAX call during an unload event will initiate the request but since the script keeps executing, the page will be terminated before any reply can be retrieved and processed from the server. With synchronous AJAX, if the user is navigating away from an e-commerce page, you can use synchronous ajax to log the user out properly in the unload event and the navigation won't happen until the transaction between the server and browser had been concluded.

How to code a Synchronous AJAX function

As you can see, a synchronous AJAX routine is very simple…

function getFile(url) {
  if (window.XMLHttpRequest) {              
    AJAX=new XMLHttpRequest();              
  } else {                                  
    AJAX=new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (AJAX) {
     AJAX.open("GET", url, false);                             
     AJAX.send(null);
     return AJAX.responseText;                                         
  } else {
     return false;
  }                                             
}

var fileFromServer = getFile('http://somedomain.com/somefile.txt');

What differentiates this from an asynchronous call is that we pass false as the third parameter in the AJAX.open method and we don't need to set up an onreadystatechange handler. The file request will be opened, sent and then the browser will hang at AJAX.send(null) until either the file has been received or the request has timed out (A process which may last more than two minutes and make it appear the browser has crashed). Like an asynchronous Ajax call, the server data will be stored in AJAX.responseText (which this example function returns), and if the server sent proper XML headers, the data will be stored in AJAX.responseXML.

How to code a Synchronous AJAX function using POST.

Of course you can send data as a POST if you need…

function getFile(url, passData) {
  if (window.XMLHttpRequest) {              
    AJAX=new XMLHttpRequest();              
  } else {                                  
    AJAX=new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (AJAX) {
    AJAX.open("POST", url, false);
    AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    AJAX.send(passData);
    return AJAX.responseText;                                         
  } else {
     return false;
  }                                             
}

var fileFromServer = getFile('http://somedomain.com/processData.php', sendThisDataAsAPost);

This sample sets AJAX.open to transmit the request as a POST, using the URL which you passed and false indicates the request will be synchronous instead of asynchronous. The requestHeader is set to tell the server we're sending data as a post, and in the send method, instead of sending NULL (nothing) we send a string called passData. Like the previous example, the browser will stall on AJAX.send() until a reply has been received from the server.

Synchronous AJAX in action

Here are two synchronous examples. The first example will fetch the requested example almost instantly, the second script will take ten seconds to run -- simulating a slow server-side script, or a bad network connection. (Note that most browsers will cache clicks while the synchronous request is processing so be careful about where you click or you can render your browser unusable if you chain click the 10 second demo).

Waiting for user action.

Synchronous Example -- No Delay
Synchronous Example -- 10 Second Delay

Conclusion

Because of the danger of a request getting lost and hanging the browser, synchronous javascript isn't recommended for anything outside of (onbefore)unload event handlers, but if you need to hear back from the server before you can allow the user to navigate away from the page, synchronous Javascript isn't just your best bet, it's your only bet!