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.

15 comments:

Shiraz said...

Nice tutorial man!
Found it from pixel2life & added it to StumbleUpon, btw.

Anonymous said...

nice tut dude... even tho i already knew some about AJAX and even used it before this tut helped me to understand it better...

fenin said...

I'm glad you guys love it :) Thanks for the support !

Anonymous said...

Hey, nice tutorial. I also found on P2L.

However, i have downloaded your example and cant get it to work. I open home.html and then it says "This text will be replaced by external content without reload". I know this is ment to happen.

But when i press index1.html or index2.html the pages content goes blank, but the links remain.

Can you please post an update.

Thanks,
Blake

fenin said...

Thanks for pointing out the mistake Blake. Due to some extraterrestrial reason i commented out, xmlhttp.send(null); statement in the example file

I have updated the example file with the corrected one.

Thanks again Blake!

Anonymous said...

Very nice tutorial dude! I found this tut on pixelgroovy.com I've been reading about AJAX for a while and this was my first try on AJAX and it worked great! Some of the other tuts out there were too much for me.:p This tut will inspire me to learn stuff about AJAX. Keep on rockin!

omochan said...

Cool stuff.

It makes me think I can actually do it :)

DataAlp said...

hey.. nice post..

but I think that you did not consider the

Error: uncaught exception: Permission denied to call method XMLHttpRequest.open error

The user needs to be prompted for the permission..

I found the solution here :
http://www.captain.at/howto-ajax-permission-denied-xmlhttprequest.php

Anonymous said...

This isn't working in IE7... Firefox works like a champ. i want to try not using frames with this code. thanks.

Krishna said...

thanks a ton dude

Anonymous said...

hi

i have try to download the zip file but link is not working


Thanks
sonu

talkholic said...
This comment has been removed by the author.
Karlotta said...

Thank you for that! I'm going to try it out on my wordpress powered site.

Hopefully I won't be back in 10 minutes with a million bugs!

Anonymous said...

Download Link not working :(

Anonymous said...

ie can not load the content of the page 2.html.it shows that it restrict the running scripts, and after allowing the blocked content it shows the page fault.what should i do???