Skip to main content

Your 30 second guide to AJAX

Posted by gvix on June 19, 2006 at 8:54 PM PDT

Chances are, if you have been building web applications for a little over a year and have used javascript even a little bit, you already know how to build AJAX applications. To use AJAX, you need to know the properties and methods of a Javascript object called XMLHttpRequest. All recent browsers support this object, but of course, as with other cross browser issues, it is instantiated differently in IE and others. The following creates this object across all browsers.

var xmlHttp;
function createXMLHttpRequest() {
  if(window.ActiveXObject) {
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  } else if(window.XMLHttpRequest) {
    xmlHttp = new XMLHttpRequest();

Now, having obtained an instance of this object, you can use it like any other Javascript object. Of course, the nice thing about it is that it can make HTTP requests to a back end process independent of the containing document or browser requests.

So the steps are:

1. Create this object.

2. Tell this object which method will handle response from the server.

// handleServerResponse is a method in your javascript code.
xmlHttp.onreadystatechange = handleServerResponse;

3. Make your request:"GET", "YOUR URL"); // can use POST or PUT as well

4. Send your request:

// the parameter to this method can be an optional request parameter

5. Handle the response from the server in the method that you designated earlier.

function handleServerResponse() {

  if(xmlHttp.readyState == 4) { // the state when the request has completed
    if (xmlHttp.status == 200) { // the HTTP status code returned from the server
      var server_response = xmlHttp.responseText; // the servers response, use this with DHTML to modify current page

Everything else that you hear about AJAX, trust me, is just clever Javascript that is used to manipulate the DOM of the current document based on this asynchronous request to the server. Your server side code is not affected (unless you are coding specifically for AJAX).

There are other methods and properties of the XMLHttpRequest object and these can be looked up here.

I couldn't believe how simple it really was. The hype around this technology is mostly to do with AJAX patterns and clever stuff that is done using asynchronous requests and manipulating the browsers DOM on the fly. So if you know how to manipulate the DOM using Javascript, you now know how to manipulate the DOM without needing to make the whole page refresh.

Related Topics >>