Ajax: A New Approach to Web Applications
by Eric Pascarello

The buzz that has been swarming the Internet is the term Ajax (Asynchronous JavaScript and XML). To my surprise, many developers still are not sure what this Ajax thing is. Hopefully I can educate those Ranchers that are still in the dark about this hot topic in the world of programming. Why is this Ajax thing so hot? Well the magic of it all is it spans every server side language out there. A PHP developer, a Java developer, and a .NET developer can all use this! This Ajax technology is not server side language specific so that is why there is great "hype." I can personally say that Ajax is not just hype. Judging by the responses I have gotten from here on the JavaRanch or out on my talks promoting Ajax in Action, it looks like Ajax is not going away, as some old timer programmers are wishing! I use it in production, and it's part of many applications that you may use on a daily basis.

It may be a surprise to some, but Ajax has been around for a long time; it's just that no one put a cleaning name to it until of late. And yes, Microsoft did implement it and others copied it (others copy Microsoft?) I am glad they did so this could take off. Ajax is supported by all of the major Web browsers now available.

This article is going to take a low level look at Ajax and see how it can help you and when you would want to use this in your application. This article is not going to give you the money to buy that brand new Testarossa, but it will give you the itching to get the keys for a test drive instead of staring at that wallpaper on your desktop. So let's stop this intro and get into the real article.

Some Ranchers looking to find information on Ajax will ask, "Where can I download the API to the Ajax language?" My response is that Ajax is not a language, but an "approach" or "methodology" to programming utilizing JavaScript's XMLHttpRequest Object. There are only a few lines of code one must use. A lot of people ask, "That's it?" These few lines of code, as we will see later on, allow you to do a lot.

An Ajax application requires knowledge of the client and server, but do not let that scare you. Ajax gives us the ability to communicate with the server without doing a traditional post back to the server. We no longer have to see the page refresh and re-render every single control of the page to check to see if there is new information. We can make double combo lists seem to fill with magic, have text pop up on the screen based on user input, and have live data show up in front of our eyes. People have been implementing this style of programming with frames, iframes, and pop up windows, but the XMLHttpRequest Object gives us a more stable and reliable way to send and retrieve the information.

Starting your engine

Now I know what you are thinking: "What is this XMLHttpRequest object you keep talking about?" It is the mechanism that drives the communication between the client and the server. For Mozilla we need one set of code, while for IE we need another. Do not worry: this cross-browser stuff is not too bad. I will give you the training wheels to get you through it.

Ajax in the Gecko browsers (Mozilla, Firefox, & Netscape), Safari, Internet Explorer 7, and Opera is based around this line of code:

var req = new XMLHttpRequest();

For Internet Explorer 5 and 6 we need to use an ActiveX constructor to get the object:

var req = new ActiveXObject("Microsoft.XMLHTTP");

All this means in the long run is we need to do a little branching to get the correct version for the browser. For right now just forget that cross browser stuff and concentrate on the object itself. Now this object has a few methods. The three that you probably will use the most are:

The two methods that are important to us are the open and send methods. You can see the open method as grabbing the keys to that Testarossa. It sets up the information on where to send that request too. The send method is us putting that key into the ignition, putting it in first, and stepping on that gas. The content is the data that we are sending to the server. It can be form data, soap messages, strings, etc. It is the information that is along for the ride just like the dealer sitting in the passenger seat with the seat belt on tight as it can go. Now one thing to remember is content size. If your content is small, you have a better chance of going fast. If your passenger weighs 600 pounds, the response to the server will be a little slow just like the reaction of that gas pedal. Now if you have a 100 pound guy in the seat, you will not notice any real lag and will have that head jerked back with that grin!

There are a few more methods that are not used as much, but can be useful. They are:

As you can see, they all deal with either getting or setting header data. And you would use the setRequestHeader if you were sending a soap message so the server knew what it was getting as an example.

Checking your instruments

We are halfway done with looking at the object. We need to examine the properties and the single event handler that the object has. Lets us just list them first. Our lonely, but very useful event handler is:

and our properties are:

The onreadystatechange event handler is rather unique. We assign it a reference to a function or assign it actual code. The function is than called multiple times during the process of making and getting the request. The calls are not random, but happen at certain states in the process. There are fives states to be exact. We can find out what state the request is in by using the readyState property. The property is an integer value ranging from 0 to 4 that inform us of the different processes being performed. The exact meanings of these states are:

When the onreadystatechange event handler achieves the state of 4 or "complete", that means we have a response back from the server. This does not mean that it was successful though. To find out if it was a success, we need to look at the status property. The status property gives use those wonderful numbers of 200, 404, 500, etc. Of course we want to see 200 for OK! If you are real bored, you can also check the statusText which is the string message that accompanies the code value. It is useful when you need to see an error message. If you are working on the file protocol (running Ajax on the desktop (file system) of your computer), you are looking for a status code of 0 (zero).

If we get the magic number of 200, we have a successful retrieval of the server side page. The processing of the data can now be started. There are two properties that allow us to get our hands on the data. The responseText and the responseXML properties to be exact. The responseText is a string value of the data returned. The responseXML is a DOM-compatible document object. What is that you are asking? In non-geek speak it is saying we can use JavaScript methods to read the data as nodes and have more control and access. Now it is up to you on what you use and is a subject for an article on its own.

Putting Ajax in gear

So now that we have just got the keys to a dream machine, let's put it together and see it working! Since we are looking at this low level, we are going to use global variables! Below is the code with some basic comments explaining it.

//Our global variable
var req;
//function that accepts the url to retrieve
function loadXMLDoc(url) {

  //set the req to false in case it is not supported
  req = false;

  //"Gecko" XMLHttpRequest object
  if(window.XMLHttpRequest) {
    try {
      req = new XMLHttpRequest();
    }
    catch(e) {
      req = false;
    }
  }
  //IE ActiveX object
  else if(window.ActiveXObject) {
    //check for newer version (there is a v3 now too)
    try {
      req = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e) {
      try {
        //older version
      	req = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch(e) {
        req = false;
      }
    }
  }

  //Make sure object is supported
  if(req) {
    //Tell function to call for state changes
    req.onreadystatechange = stateChange;
    //Give it the keys specifying GET or POST
    req.open("GET", url, true);
    //Since we are using GET no info to send
    req.send("");
  }
  else{
    //inform user that it is not supported!
    alert("This browser lacks Ajax support!");
  }

}

//Handles the state changes
function stateChange() {
  //Look for the complete state of 4
  if (req.readyState == 4) {
    //Make sure status is a success
    if (req.status == 200 || req.status == 0) {
      //display content
      alert(req.responseText);
    }
    else {
      alert("Retrieval Error: " + req.statusText);
    }
  }
}

And that is all you need to make the request to the server. I guess you want to see how you can call this code. Well one way you can do it is in a form like this.

<form name="Form1" onsubmit="loadXMLDoc(this.t1.value);return 
false;">
  <input type="text" name="t1" value="test.txt"/>
  <input type="submit" name="sub1" value="Check Request"/>
</form>

I was kind enough to zip up the example for you too so you can play with the code. You can download it here on my JavaRanch blog: http://radio.javaranch.com/pascarello/files/BasicAjaxExample.zip

Putting the pedal to the metal

Now you want to know how can I get away from this global scope and move into the OO world. Well you can look at examples on my blog that use one of the content loaders from Ajax in Action or you can look at many of the frameworks out there that have OO based code. The global aspect is not bad, expect it can only handle a single response at a time.

Now that all of the excitement of the code is over with, we can step back and let reality set back in. OH MY! AJAX IS JAVASCRIPT! AH! I NEED TO REWRITE MY WHOLE APPLICATION! All I can say is calm down and take a look at these causes for heart attacks.

Some people that are afraid of Ajax think they need to redesign the entire way/approach/method on how they program a web application. In reality that is not the truth at all. All of the same basic principles apply to an Ajax application such as security, business logic, and database access. The only real difference is to rethink how certain controls will work. Just because you adopt Ajax does not means the entire page can not post back. A single Ajax powered control on the page is all you need to improve a page's performance. A double combination selection list on the page can easy be transformed and powered by Ajax. A type-ahead textbox script can help users eliminate keystrokes when using a phone book look up and so forth. One little Ajax application can save a user time! You will look smart to the executive boss that saved 10 seconds in their busy golf filled schedule to find the name of one of the clients that he has a 10AM tee time with.

Now you may be concerned that Ajax is based on the XMLHttpRequest Object which is JavaScript. "I do not know JavaScript and I do not want to know all of the little quirks of the browser." That is a common thought I get in my talks. Well if you do not want your daily routine to be visiting sites like www.quirksmode.org, than you are in luck. There are tons of very good frameworks out there all based around your language. If you are working in Java, Ruby, or .NET, you can find a framework that fits your need. Do a search on Google and you will not have any trouble finding one!

Now that you are all fired up about this Ajax stuff, you may want to know where can I get more information. All I can say is the web is full of stuff. You can see two sample chapters of Ajax in Action here: http://www.manning.com/books/crane/chapters. You can see all of the breaking news on Ajax at www.Ajaxian.com. You can post questions directly to me at the HTML and JavaScript forum here on www.JavaRanch.com and you can look through my blog http://radio.JavaRanch.com/pascarello for more articles on Ajax.

Move into the world of the client side merging with the server and see how you can improve your users' experience. Remember to do it one control at a time and keep your code clean!