Friday, October 27, 2006

Ajax Quickstart tutorial

Personally, when i start learning something new, i would usually just skip the text and read the code first.
So in this tutorial, im gonna put the code first. For most of you , this would be more than enough . The purpose of this tutorial is to make you 'Ajax aware' in the least possible steps. And here we go.

End result: fetch content from external docment, and update the existing document without reload[without reload! thts the keyword]


<html>
<head>

<script>

//create a XMLHttpRequest Object.
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

//call this function with url of document to open as attribute
function requestContent(url) {
xmlhttp.open("GET",url,true);
xmlhttp.onreadystatechange =statusListener;
xmlhttp.send(null);
}

//statusListener function is called automatically whenever readystate value of XMLHttpRequest Object changes.
//see xmlhttp.onreadystatechange =statusListener; statement above.
//When readystate is 1, its a loading state.
//When readystate is 4, content is loaded
function statusListener() {
if (xmlhttp.readyState == 1) {
document.getElementById('content').innerHTML="loading..";
}

if (xmlhttp.readyState == 4) {
//xmlhttp.responseText is the content of document requested
document.getElementById('content').innerHTML=xmlhttp.responseText;
}
}
</script>

</head>

<body>
<a href='javascript:requestContent("1.html");'>1.html</a> <a href='javascript:requestContent("2.html");'>2.html</a>
<div id="content">This text will be replaced by external content without reload</div>
</body>
</html>




Explanation:

The whole Ajax thing starts with the creation of an instance of XMLHttpRequest object.
For firefox,new XMLHttpRequest(); will create one, and for IE,new ActiveXObject("Microsoft.XMLHTTP");

The stuff in requestContent function does the job of initiating the call, and listening to progress.

statusListener function is called whenever onreadystatechange value of Object changes. When its is 4, ie. xmlhttp.readyState == 4, the loading is finished.

Use document.getElementById to replace a divs content with the new content.



update: If you need further detailed explanation , feel free to take a look at this post.

This code was originally written somewhere in mid-2005, based on the famous Ajax tutorial in Apple Developer Connection.In real world scenario, instead of a plain file[as in this example], you will be calling a server side script that returns xml formatted data[After all, thats the X in Ajax is!],which should be parsed through.This is described in the second version of this tutorial[another quick one ;) ].



Download example zip [If the link is not working, just leave a comment.]

Apple developer Connection article.