'Hello World' using AJAX

“Asynchronous Javascript And XML” is a mouthful for a web technology that’s in wide use these days. Simply put, it lets a web page download more content without reloading the page, and relies on a magic Javascript object called an XmlHttpRequest to do the work of requesting more data in the background, so it can fill in things on the page.

So, fiddling with AJAX, let’s do a little Hello Worlding:

Here’s a button, that when clicked, calls the “startRequest()” function in some javascript behind the entry:


And here’s a div:

<div id="ajaxtest">
<em>(although you can't see it as a separate div,
this text will be replaced)</em></div>
(although you can’t see it as a separate div, this text will be replaced)

Go on, watch the div text above, and click the button.

Here’s the javascript:

var xhr;
if (window.XMLHttpRequest){
  xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject){ // in case it's IE
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
 }
// set up the callback
xhr.onreadystatechange = function(){
  myDiv = document.getElementById("ajaxtest");
  if(xhr.readyState  == 4) {
  if(xhr.status  == 200){
   myDiv.style.background = "green";
   myDiv.innerHTML =  xhr.responseText;
  } else {
   myDiv.innerHTML = "Error: " + xhr.status;
  }
  }
}
function startRequest(){
  xhr.open('GET', '/ajaxtest.php', true);
  xhr.send(null);
}

Firstly, the code sets up a variable xhr, which contains the magical object. This is the XmlHttpRequest object, and is responsible for communicating from the live Javascript to the back end server.

The request object is first set up at the script’s execution, but the only thing we do with it is tell it what to do when its “ready state” changes; that is, when the request shifts from not initialised, to set up, to having been sent, to being in process, to completion.

These states are numbered 0-4 respectively. Hold that thought; we’ll use it later. Suffice to say that, on the script’s execution, we now have an otherwise anonymous function that will be called when the ready state changes.

Now, in order for something interesting to happen, we click the button. That kicks off startRequest(), which in turn sets up a asynchronous request to ajaxtest.php, and submits it with no parameters (that’s the null). Asynchronous means we don’t sit around waiting for a response, and that’s why we need the readystatechange callback function.

So, when something interesting happens to the xhr object, the ready state changes (e.g. when we get a response back after sending our request). The browser then executes the anonymous function: first, the function checks that the request is complete – remember Ready State 4 above? don’t forget the ready state changes several times per request. We only want to read the response text once, at completion. Once the function has checked the request has been successfully completed, it then uses the xhr’s response-text to fill in the div called “ajaxtest”.

Et voila, we have “Hello World” in AJAX.

Advertisements