A beginners guide to AJAX

25th June 2008

AJAX stands for "Asynchronous JavaScript and XML". What AJAX lets you do is send and receive data to and from a remote source, and render it in your application, without reloading the page.

If you know your JavaScript this will be a piece of cake for you. If you don't know JavaScript you should start by mastering that. As this is a beginners guide I'll keep things simple and demonstrate with an easy example.

Let's create a page that asks for the users name, checks if we have data on the user and renders the information if data was found. The page will just have a textfield and a submit button. Below that we'll add a div where we can output the information returned.


Enter your name:
<input type="text" id="name" name="name" />
<input type="button" value="Submit" onclick="sayHi()" />
<div id="content">
Type in your name in the textfield above and hit submit.
</div>

Notice that I have assigned an id to the textfield and the div. We are going to need this to retrieve and insert data into these elements. We'll create the "sayHi()" function in a while. First let us create a simple PHP script that will check the users input and return data.

For the purpose of this example I created a simple PHP script that checks if the name is "Farid", if it is it will echo a CSV (comma-separated value) that looks like "1,1983,Mumbai". If the name is not "Farid" the script will echo "0". The first string means "found data, born in 1983, born in Mumbai". The second string translates to "no data". This PHP script could have been as complex as necessary. It could have hit a database to actually check for the user and it could have returned a lot more data. For our example this is good enough.


$name=$_REQUEST['name'];
if($name=='Farid') {
echo '1,1983,Mumbai';
} else {
echo '0';
}

AJAX is all about the XMLHttpRequest object. This object will be communicating with your server whiles the user is surfing your page. Below is a JavaScript function that will try to create this object in three different ways, the first is for most browsers and the last two are for IE. We want our applications to work cross-browser and this function does its best to take care of that. If it fails to create the object it will alert a message saying "Error initializing XMLHttpRequest!".


function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request) {
alert("Error initializing XMLHttpRequest!");
}
}

Now that we have a function to create our object we can use it when and where we need it.

Our "sayHi()" function will get the users input from the textfield when the user clicks on submit. It will then check if the field is empty, a very simple check here. If the field is empty it will alert "Please enter your name.". If the user has entered a name "sayHi()" will send that information to our PHP script to check if we have data on that user. Our PHP script will reply saying yes or no and our "sayHi()" function will act accordingly. If data was found the function will output that in the div below the form, if data was not found a sorry message will be rendered instead.


function sayHi() {
var name=document.getElementById('name').value;
var contentDiv=document.getElementById('content');
if(!name=='') {
var draw='Hey there '+name+'.<br />Give me a second to look you up..';
contentDiv.innerHTML=draw;
createRequest();
var url = 'ajax-data.php?name='+name;
request.open("GET", url, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200) {
draw='Hey there '+name+'.<br />';
var data=request.responseText.split(',');
if(data[0]==1) {
draw+='You were born in '+data[1]+' in '+data[2]+'.';
} else {
draw+='I\'m sorry, I found no data on you.';
}
contentDiv.innerHTML=draw;
} else if (request.status == 404) {
alert("Requested URL does not exist \n"+url);
} else {
alert("Error: status code is " + request.status);
}
}
}
request.send(null);
} else {
alert('Please enter your name.');
}
}

As you can see we are calling our "createRequest()" function from here. In the line below "createRequest();" we are creating a variable and assigning the URL to the script we want our object to communicate with. We are sending the value entered by the user as a parameter, that variable is created in the first line of our function.

Below that we are telling the object to send a request using GET, send the request to the URL defined above, and that it is to be an asynchronous request. We can simply use "request.open()" in this line because we called our "createRequest()" function above that creates the "request" variable with the XMLHttpRequest object assigned to it.

The line below that, "request.onreadystatechange", is where we tell our function what to do once we have a response from the PHP script. The first line in that function checks to see if the "HTTP ready state" is 4. There are five different ready states, 0-4, and 4 means the server is done processing the script and it's now safe to get the response.

The second line in that function checks to see if the "HTTP status code" is 200. 200 means ok. 404 means page not found. If the status is 200 we check the response using "request.responseText" and do whatever we want with it. In our case we are splitting the response text on "," and checking if the first value is 1. If it is 1 we are appending the data to a variable called "data" that we later will use to insert text into the div below the form using ".innerHTML". If the first value is not 1 we append the string "I'm sorry, I found no data on you." instead. If the status code is not 200 but 404 we alert a message saying "Requested URL does not exist [url]". If the status code is neither 200 or 404 we alert a message saying "Error: status code is [code]".

Now that our function knows where to send the data and what to do with the response, we send this request using "request.send(null);".

There is a great series on AJAX written by Brett McLaughlin. It can be found on the IBM developerWorks web site. I strongly recommend reading it if you are interested in AJAX. Here is a link to their "Technical library" with all the articles of the series, all but Part 3 which is missing there for some reason.

Did you enjoy this post?

If you enjoyed this post you can subscribe to my RSS RSS feed to know when I post another article. It would also be great if you bookmarked this post on your favorite social bookmarking site, if you have signed up with any.



Comments

  • Anonymous said:

    Bookmarked and saved as .pdf.

Leave a comment