So I’ve been trying to drill the super simple concept of AJAX into my head for months (sadly) now. Anyways I think I finally got it down enough to explain it. I know there are libraries out there that can do it for you without any thinking at all. But it is my belief that a developer MUST understand how to build an application’s functionality from scratch if he/she has to. In this post I will explain how to use an XMLHttpRequest object in conjunction with the form’s ‘GET’ method to retrieve data from the server. In our example application we will push a button passing the message ‘Marco’ to the server which will then return the message ‘Polo’ back to us. So let’s begin!
1. Make XMLHttpRequest Object
This is the most important thing. It is what AJAX is all about, it is the object that fetches stuff for you to display on your web pages. Without it (and well along with the user having JavaScript enabled) basic AJAX is not possible. I know there are “workarounds” that might give the impression of AJAX but I am just talking about straight-up AJAX. Anyways, the XMLHttpRequest object is important, so it is understandable it must work on every browser. I hope I didn’t lose you. This is how we do it.
var req = null; // XMLHttpRequest Object
var init = function() {
try { // firefox, safari, ie7
req = new XMLHttpRequest(); }catch(e) {
try { // later ie
req = new ActiveXObject('MSXML2.XMLHTTP');}catch(e) {
try { //early ie
req = new ActiveXObject('Microsoft.XMLHTTP');} catch(e) {
return false;}}}
return req;
}
So what did we do here? If you look past all the ‘try’ you notice that we try to declare the ‘req’ object as whatever form of XMLHttpRequest is available depending on your browser. In older versions of Internet Explorer AJAX occurs in the form of ActiveXObjects. This explains most of the clutter in the preceding code.
2. Open The XMLHttpRequest
So you made the object now you need to tell it what to fetch. For this we use the open method of the XMLHttpRequest object which takes three parameters: method (get or post); url, and whether our request is asynchronous or not. What asynchronous means is allowing to happen at different times.
Additionally you have to execute the ’send’ method of the request object passing a null value. The ’send’ method ships our request to the server, the value it takes is used for POST requests which is why we pass null this time. This is what it looks like.
req.open('GET', 'index.php?call=Marco', true);
req.send(null);
For simplicity’s sake in our example we are going to use the form’s ‘GET’ method to request text from the server as opposed to XML. Using the form’s ‘POST’ method is a little more difficult and requires additional code. I will later explain how that is done in another post.
Another thing you might want to know is that some browsers might try to cache the response you received from the server. So no matter how different the response you are expecting is, it returns the same one always. To avoid this you might want to try append the time the request was made to your ‘URL’ string as so.
var time = new Date();
req.open('GET', 'index.php?call=Marco&time=' + time.getTime(), true);
req.send(null);
Note
Also please note that AJAX will only work within the server that made the request so make sure the ‘url’ value you pass is a local one. Cross server AJAX requests are not readily possible for security reasons but can be allowed through additional server configuration.
3. Check For The Request’s State Change
Now the next few steps might get a tiny bit complicated. I will try extra hard to simplify them.
First we want to try to monitor the ‘onreadystatechange’ event of the XMLHttpRequest. The ‘onreadystatechange’ event tells us when there is a change of state in our request as the name already suggests. So we are going to listen in by making an event handler for it.
req.onreadystatechange = function() {
...
}
However the ‘onreadystatechange’ event handler itself won’t really tell us anything. The reason being that there are four states the request can move around from which won’t necessarily hold the data we want. They are listed below. For our purposes we only care about state #4 which means our data is ready for our viewing.
- Uninitialized (0)
- Loading (1)
- Loaded (2)
- Interactive (3)
- Completed (4)
So in order to check when our state is at 4, we create a simple conditional statement within our event listener.
req.onreadystatechange = function() {
if (req.readyState == 4) {
...
}
}
But again we need more since it is not enough for us to know when AJAX has something to show us. The reason is that it might have encountered an error and we wouldn’t want to show that to the users right? So now we must check to see if everything worked out right and that there were no server errors or anything of the sort. There are two ways to do this. One is to make sure our request’s status (req.status) is greater than or equal to 200 and that it is also less than or equal to 299. Together with the rest of our state change code it would look like this.
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status >= 200 && req.status <= 299) {
...
}
}
}
A more simple alternative to the last step we did is to check if the 'statusText' property of our request simply returned 'OK'. For the sake of our Ajax In A Nutshell post name we will stick with the alternative. This is what that looks like.
req.onreadystatechange = function() {
if (req.readyState == 4) {
if(req.statusText == 'OK') {
...
}
}
}
Now wasn't that a lot easier?
4. Retrieve Your Data
Finally we grab our much awaited data which will be stored in our request's 'responseText' property. I suggest you structure your main function to accept a handler function for the data. This handler function would then either further process the data and or place it on the HTML document for viewing. In our example we are going to be passing our data to another function (our handler function) which will display it on a div in our HTML document. Below is what the passing of our data to the 'handler' function will look like along with our state change code from before.
req.onreadystatechange = function() {
if (req.readyState == 4) {
if(req.statusText == 'OK') {
dataHandler(req.responseText);
}
}
}
So there it is. Getting your data from the server wasn't that hard. Hopefully you are not like me and actually get it on the first few reads.
Sample Please?
I have built a sample page and script that uses this code to submit a form to the server. The form will just submit the hidden value "Marco". The server will then respond "Polo" which will be displayed on a DIV below the button.
You can see the sample demo here: http://www.quinterox.com/public/ajax_sample/
You can download the sample files here: ajax_sample (21)


August 8th, 2009 at 3:16 PM
Hi, Onload of page my antivirus put alert, check pls.
Thanks
August 8th, 2009 at 8:48 PM
Hey Zoran,
Thanks for letting me know. I have run some tests and am getting nothing. Here are the results.
http://online.us.drweb.com/cache/?i=d8df7ae7eeb367e56b3aa9cc764ab797
http://www.google.com/safebrowsing/diagnostic?site=http://www.quinterox.com/
I will continue investigating though. Thanks.
Cesar