Asynchronous AJAX Calls

The "A" in ajax stands for asynchronous. And yet, not all ajax calls are as asynchronous as they could be. For example, click on the clink below.

Get date with 5 second delay synchronously

Now try to click around your browser. You can't. Your browser will be locked for 5 seconds after you clicked on that link. You see, JavaScript is single-threaded so it will sit and wait until the call is finished before it will run anything else. Normally this is not too big of a deal, but just to be a jerk, I wrote the server call with a 5 second sleep:

<?php sleep(5); echo date('M d, Y'); ?>

Here is what the JavaScript looks like:

function getDate() { oXhr = new XMLHttpRequest(); oXhr.open("GET", "datep.php", false); oXhr.send(null); alert(oXhr.responseText); }

To keep your users' browsers from freezing if your ajax calls take too long, you should write the request in this manner:

function getDateA() { oXhr = new XMLHttpRequest(); oXhr.open("GET", "datep.php", true); oXhr.onreadystatechange = function() { if (oXhr.readyState == 4) alert(oXhr.responseText); } oXhr.send(null); }

Now try it:

Get date with 5 second delay asynchronously

Much better, huh?