JavaScript LogoUnderstanding the basic components of an AJAX request / response, and being able to write it all out by hand is an important skill for any JavaScript developer to have.

Yeah yeah yeah, you’ve used jQuery.ajax(). But can you write AJAX code by hand, starting with a blank sheet of paper? While some might feel that jQuery, DoJo and other popular libraries abstract these kinds of details just fine, it’s important to understand what is happening under the hood.  So, give me a moment to step down from my soapbox.js and let’s jump into the code.

The XMLHttpRequest Object

The XMLHttpRequest object is the key to AJAX. It is a constructor function that is a property of the window object. You instantiate this object, and then take advantage of the various properties and methods of the instance object that is returned.

Determining Support for the XMLHttpRequest object

Previous to Internet Explorer version # 8, there was no support for the native XMLHttpRequest object. You had to instantiate IE’s ActiveXObject(), and pass in the argument: “Microsoft.XMLHTTP”. Even though the IE6 and below audience is dwindling, someone out there is still using IE6 or IE5, so it’s a good idea to handle that scenario gracefully.

Example # 1

In Example # 1, we use an IF/ELSE block to determine support for the XMLHttpRequest object. If it is supported, we instantiate the object and if not, we instantiate IE’s native ActiveXObject object.

The onreadystatechange Event

Of the eight events fired by the XMLHttpRequest object, the one we tend to care about most is the onreadystatechange event. It indicates the “readiness” of the XMLHttpRequest object’s request. A ready state of four (4), indicates that the XMLHttpRequest object’s request has generated a response, and that response is in the browser, and ready to be consumed.

The status Property

XMLHttpRequest object’s “status” property represents the HTTP status code returned by the server when our XMLHttpRequest object’s request was sent. There are numerous HTTP status codes that can be returned by a web server, but a detailed discussion of them is outside of the scope of this article. Simply put, we are most often only interested in an HTTP status code of “200” which means: “ok”. It is the web server’s way of saying: “I have completed your request, here it is, and there were no problems”.

So, the combination of an XMLHttpRequest object readystate of 4, and HTTP response code of 200 is the scenario we want. This scenario means that our request was returned, it is ready and there was no problem with the request. Once we know that this condition exists, then we can do something with whatever was returned by the XMLHttpRequest object’s response request.

req.onreadystatechange = function(){ if (req.readyState === 4 && req.status === 200){ //if readyState is “4” and the server response was 200/ok… //inject the returned HTML into the DOM document.getElementById(‘target’).innerHTML = req.responseText; }; };

Opening the XMLHttpRequest Object’s Request

So far, nothing has happened. All we have done is instantiate the XMLHttpRequest object, and set up a function that will execute when we know that the request’s response is “ready” and there was no problem with the request. Now we will open the request.

When calling the open() method of the XMLHttpRequest object, we pass in three arguments:

  • The type of request (“GET” or “POST”)
  • The URL that the request should be set to
  • If the request should be sent asynchronously (you will almost always want this to be “true”)

Sending the XMLHttpRequest Object’s Request

So this is the final step in writing an AJAX call: sending the request. There is nothing more to do than simply execute the .send() method:

Now let’s look at the markup we’ll need for the article’s example. Below you’ll see two buttons. One will kick off the AJAX request, and the other simply clears the contents of the page. There is also a DIV with an id of “target”. That is the element in which our AJAX request’s response text is injected.

We also have some JavaScript that sets up event handlers for the button clicks. When clicking the button with the ID of “click”, the AJAX request is kicked off and the requests response text is injected into the DIV with the ID of “target”. When clicking the button with the ID of “clear”, the “target” DIV’s contents are cleared.

It is not critical to be aware of the server page’s code for this very simple example, but in case you are interested, it is a simple PHP page that sends a message that includes the time of the request, allowing us to verify that the requests are being made in real time.

Server Code

Below is the full working code for our AJAX eample:

Example # 2

Here is a link to the full working page for this article’s example:

http://examples.kevinchisholm.com/ajax/example-1/

Summary

In this article we discussed the XMLHttpRequest object. We learned how to test for the browsers support of this object, instantiate it and assign an anonymous function to handle its onreadystatechange event. Inside of that function, we learned how to check for the readyState property value, the status property and then inject the return text into the DOM. We also discussed how to open the XMLHttpRequest object’s request, and then send it.

Hand-coded AJAX is no big deal, and I’m hoping that this article has left you feeling this way. The key is getting to know the XMLHttpRequest object, specifically its various properties and methods. There is plenty more to talk about with regard to AJAX in native JavaScript, but what we covered in this article is the bare minimum needed to get up and runing.

Helpful Links for hand-coded AJAX

What’s the difference between jQuery.ajax(), jQuery.get() and jQuery.post()?
Using the jQuery Promise Interface to Avoid the AJAX Pyramid of Doom
Using jQuery Deferred to Manage Multiple AJAX calls
What Are the Top 10 JavaScript Links for AJAX ?