Rasmus' 30 second AJAX Tutorial
Posted by Raj Shekhar in
programming
Thursday, July 28. 2005
I was reading through the mails in the php-general mailing list and came across this mail by Rasmus about AJAX
I find a lot of this AJAX stuff a bit of a hype. Lots of people have been using similar things long before it became "AJAX". And it really isn't as complicated as a lot of people make it out to be. Here is a simple example from one of my apps. First the Javascript: function createRequestObject() { var ro; var browser = navigator.appName; if(browser == "Microsoft Internet Explorer"){ ro = new ActiveXObject("Microsoft.XMLHTTP"); }else{ ro = new XMLHttpRequest(); } return ro; } var http = createRequestObject(); function sndReq(action) { http.open('get', 'rpc.php?action='+action); http.onreadystatechange = handleResponse; http.send(null); } function handleResponse() { if(http.readyState == 4){ var response = http.responseText; var update = new Array(); if(response.indexOf('|' != -1)) { update = response.split('|'); document.getElementById(update[0]).innerHTML = update[1]; } } } This creates a request object along with a send request and handle response function. So to actually use it, you could include this js in your page. Then to make one of these backend requests you would tie it to something. Like an onclick event or a straight href like this: <a href="javascript:sndReq('foo')">[foo]</a> That means that when someone clicks on that link what actually happens is that a backend request to rpc.php?action=foo will be sent. In rpc.php you might have something like this: switch($_REQUEST['action']) { case 'foo': / do something / echo "foo|foo done"; break; ... } Now, look at handleResponse. It parses the "foo|foo done" string and splits it on the '|' and uses whatever is before the '|' as the dom element id in your page and the part after as the new innerHTML of that element. That means if you have a div tag like this in your page: <div id="foo"> </div> Once you click on that link, that will dynamically be changed to: <div id="foo"> foo done </div> That's all there is to it. Everything else is just building on top of this. Replacing my simple response "id|text" syntax with a richer XML format and makine the request much more complicated as well. Before you blindly install large "AJAX" libraries, have a go at rolling your own functionality so you know exactly how it works and you only make it as complicated as you need. Often you don't need much more than what I have shown here. Expanding this approach a bit to send multiple parameters in the request, for example, would be really simple. Something like: function sndReqArg(action,arg) { http.open('get', 'rpc.php?action='+action+'&arg='+arg); http.onreadystatechange = handleResponse; http.send(null); } And your handleResponse can easily be expanded to do much more interesting things than just replacing the contents of a div. -Rasmus
Raj Shekhar - #1.1 - 2005-07-30 07:46 -
Definately. Reading his mails on the php-general mailing list always makes go "aha! that is cool/simple"
gregor-e - #2 - 2005-07-30 00:22 -
Awesome explanation. You could do a whole book of these and make a mint!
Raj Shekhar - #2.1 - 2005-07-30 07:50 -
Rasmus has a book "Programming PHP" by o'reilly publishers. I have not read it, but I can guess it would be good.
Thank you for this. The multiple parameter part is exactly what I was trying to figure out!
Jacques - #4 - 2005-07-31 19:38 -
Nothing like to know the things! I try implemate this with a PEAR QuickForm setDefaults method to fill a field on the tab...
chuck - #5 - 2005-08-01 06:02 -
can you recomend a good lightweight javascript xml parser that works on all major browsers?
thanks
Raj Shekhar - #5.1 - 2005-08-01 20:47 -
I am not a javascript programmer and I usually use php/perl to get the job done. Frankly, if I had to parse xml, I would try to do it in php .
Nik Cubrilovic - #5.2 - 2005-08-03 15:43 -
He is talking about parsing XML respones, which you cant do on the server side. In his example, Rasmus uses responseText, but you want to use responseXML, which is a DOM object which you can then manipulate with the standard DOM functions (its dom walking, not event-based parsing like most people do in PHP). PHP might have 1000 different ways to do things but there is one way to parse XML in Javascript and that is it. An example (in line with the code above) would be:
var responseNode = http.responseXML.getElementsByTagName("response")[0];
Which will take anything below in the response XML (I just happen to use in my code) and then you can walk the child elements etc. I would also alter the way Rasum detects which object to use to establish the http connection, since there are also two types of ActiveX object for IE.
Jonas Geiregat - #7 - 2005-08-08 14:48 -
Thanks great post!
But I don't like the browser detection code , I'd rather use something like
if(window.XMLHttpRequest) {
try {
var req = new XMLHttpRequest();
} catch(e) {
var req = false;
}
} else if (window.ActiveXObject)
and so on ...
Dave - #8 - 2005-08-09 04:40 -
MAYBE YOU SHOULD LEARN HOW TO CODE PHP...
Scott Pobiner - #9 - 2005-08-12 08:26 -
I noticed a problem with this code on my mac using firefox and safari. I use code similar to the above and for some reason the returned value was not matching my ID. I tried everything except the most simple and obvious... it seems that the php was returning two leading characters that was screwing with the explicit matching used by "getElementById" once I did a .substr(2) everything started working!
Three days of searching... ugh!
Has anyone else noticed things like this?
p
Raj Shekhar - #9.1 - 2005-08-13 08:17 -
Try posting on the php-general mailing list. Someone might have run across this problem. Or the problem might be in the way you are returning the strings
YeJun Su - #10 - 2005-08-18 08:54 -
Hi,I'm a Chinese student.
I was impressed on your article at the first eyes on that.
It helped me very much.I was finding something about AJAX everywhere on the Internet.Thank you very much.
Now I'm a java programmer only able to develop easy web component.Your article makes my eyes open.
Wish you good health
Jeff - #11 - 2005-08-20 01:44 -
Nope, this didn't work for me when I tried it. Why not give a simple AJAX "hello world"? Nobody ever does that, and that's what I really want. I've been trying to get AJAX wrapped around my head, but I just can't....for 3 weeks. I'm begging the world for a "hello world"
Joshua Colson - #11.1 - 2005-08-20 05:29 -
Just for you:
http://www.voidgate.org/~jcolson/ajax-hello-world.zip
You'll need a webserver that can run PHP. Just unzip the file into a directory that will execute the PHP and you're off.
HTH
John - #11.2 - 2005-08-20 13:15 -
http://www.phpclasses.org/browse/package/2520.html
File: pajax-2005-08-16.tar.gz
Size: 10877
Detailed description:
This class can be used to make the browser invoke actions executed on the server side without reloading the current page.
It sends what is known as AJAX requests that consist in Javascript calls that sends HTTP requests to the server encapsulate the eventual parameters of the requested actions.
The class generates Javascript code with a behavior that can be customized by the developer using event handler functions also in Javascript.
On the server side the class can handle the requests dispatching the invoked function and passing eventual parameters.
The class supports requests done using both GET and POST methods.
Nathan - #12 - 2005-08-22 13:50 -
Good simple example. There is a bug lying in wait though with the multiple parameter example -- you probably want to escape the variables you are passing through GET with the javascript 'escape' function.
- Nathan
Anonymous - #13 - 2005-09-01 22:46 -
informative tutorial.
There is similar tutorial up but in my opinion much better (uses object detection not browser detection for cross browser compatibility and has better validation):
http://aleembawany.com/weblog/webdev/000051_ajax_instant_tutorial.html
Richard - #14 - 2005-09-05 11:13 -
Nice. Very ground-level, no-bullcrap overview of what AJAX does on the surface.... and you're right, people have been implementing various nondescript flavours of AJAX for ages... for instance, I've been using iframes to do asynchronous postbacks/updates and DOM manipulation for over a year.... only now someone's gone and made up a pretty acronym for it. Heh, and to think I was weeks away from doing up a proper spec for it and everything to use in my projects.
Still, having standards isn't a bad thing, as long as they serve a useful purpose. I think AJAX is a good way of standardising and unifying a fairly basic mish-mash of methodologies for creating truly dynamic web pages. I'll be keeping an eye on AJAX for sure.
wtanaka - #15 - 2005-09-06 09:05 -
The important part about the hype is that people are using it, which will make it more stable and standard.
Nader - #16 - 2005-09-06 14:01 -
A couple of months after your enlighting post about AJAX we have finally used the technology to boost our project Bandnews.org . It works!
Thanks again, keep up the great posts on your blog, Nader
Jeff Garbers - #17 - 2005-09-06 19:35 -
I'm just getting started with this stuff... the code worked on Firefox, IE, and Safari, but not in Opera. Is there a trick to get it to work there?
Jeff Garbers - #17.1 - 2005-09-06 19:41 -
Found the answer to my own problem... by replacing the browser detection code with object detection code, Opera 8.0 works fine. Just replace the logic in createRequestObject with
var ro;
ro = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
return ro;
Jeff Garbers - #18 - 2005-09-06 19:48 -
Okay, here's another problem. If rpc.php's output is not "idempotent" -- that is, if it can be different even given the same input value, like maybe it includes the current time -- IE's caching mechanism prevents it from being fetched. For example, if rpc.php returns time(), you can click the [foo] link over and over and the time won't change from the first time it was fetched. How can we guarantee that IE won't cache the stuff it fetches on the request?
Steve B. - #18.1 - 2005-09-07 16:14 -
Jeff - good question. I had the same issue. I changed the get line to:
http.open('GET', 'process.asp?rnd=' + Math.random()*4 +'action='+action);
Works great! Take care,
Steve
Jeff Garbers - #18.1.1 - 2005-09-07 18:53 -
Steve - I found another solution, too. Add these two lines to rpc.php before any other output is generated:
header("Cache-Control: no-cache");
header("Pragma: nocache");
I think this is perhaps more in line with "official" HTTP methodology, but your fix is pretty clever!
PhilB - #18.1.1.1 - 2005-09-15 10:51 -
The best way I found to cache-bust was to add a meaningless and random variable to the requested URL; it isn't mentioned specifically in my tutorial at www.mousewhisperer.co.uk/index.php?page=ajax as I thought it was outside the scope of the piece, but open the demos window and view the source of the page; the relevant lines are commented //cache buster
Dave - #19 - 2005-09-06 20:45 -
That shows nicely what AJAX is about, now that it has a name, but I'm not so sure about the roll-your-own approach. If you have a semi-complex app, you're going to end up writing your own framework anyway, so just find a good library that lets you point at a file upload input and go "doAJAXStuff".
Raj Shekhar - #19.1 - 2005-09-07 16:11 -
It depends on what the problem is that you are trying to solve. Sometimes it happens that you need 10 lines of code rather than a complete library or a framework to get your job done. Joel has a nice essay about this where he expalins it a bit more clearly www.joelonsoftware.com/articles/fog0000000007.html
Piotr - #20 - 2005-09-07 12:06 -
I don't know javascript but it seems to me that
if(response.indexOf('|' != -1))
should be
if(response.indexOf('|') != -1)
Steven - #20.1 - 2005-11-06 02:13 -
You're right, I tested it out myself and that is indeed a syntax error. I figured the same thing out you did and was about to post it until I saw you found it too.
Olli - #21 - 2005-09-07 13:29 -
See http://weblogs.asp.net/mschwarz/ or at his web site http://ajaxpro.schwarz-interactive.de/
.
Joe - #22 - 2005-09-10 03:38 -
Great job! It's a neat example about the core of AJAX, which is "XMLHttpRequest()" in Javascript. It helps to get rid of some of the clouds around AJAX because of hyping.
But personally I see the AJAX is more than a dynamic method to communicate with server. When you have a more complicated application, the "X" in AJAX will be very important, which is using XML to handle complicated client/server data exchange.
To me, overhyping and over-simplified are both not good.
Sumit - #23 - 2005-09-16 17:25 -
Wonderful (*Article*) -- (*Really Great, Superb*), Never New Ajax wud be so easy to start...!!
cannibal - #25 - 2005-09-26 12:26 -
WONDERFULLLLLLLL....
THE GREATEST TUTORIAL EVER!! THANKS
Anonymous - #26 - 2005-09-30 08:28 -
The best tutorial to start with AJAX, thx for that
Derf - #27 - 2005-10-14 16:36 -
Excellent tutorial! I managed to get this up and working in minutes on my site, but then it broke when I started trying to get it to do more complex things.
It turns out that apparently Javascript expects a newline at the end of the response, otherwise responseText will not contain the response (not sure if it drops the whole response, or just the last line, I'm only sending one line) (both IE and Moz appear to require this). With the script shown, it doesn't matter, when PHP reaches the end of the script it adds a newline for you.
I added exit(); to the PHP script which is what triggered the problem. If you use exit();, you must print the newline yourself.
tripdragon - #28 - 2005-10-28 16:05 -
Please forgive me, but how can this load in something more? Like a web page or tags of code ?
fish Mysterious as an example ?
Alan Jacobs - #29 - 2005-11-04 15:10 -
Hi Rasmus, nice Tutorial .
I'm trying to parse the responseXML property of some "Microsoft.XMLHTTP" ActiveXObject after sending a request using DOM, but I find it empty (no tags). I mean, the following JavaScript code alerts an xml string for responseText but 0 (zero) for responseXML.
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.Open("GET", myUrl, false);
xmlhttp.send();
alert(xmlhttp.responseText ); // Ok!!
alert(xmlhttp.responseXML.getElementsByTagName('*').length); // Zero :-((
Any idea why?
Thanks,
Alan.
ygor - #30 - 2005-11-05 11:31 -
Great example. Thanks.
brad wright - #31 - 2005-11-11 19:53 -
This code doesn't seem to work with IE. I created a simple web app based on this code:
www.imipolex.org/ajax/misc/triptych.php
When I open it with Firefox everything works fine. With IE, all the buttons work properly the first time I cilck them (i.e. the correct part of the page reloads). After the first click though, clicking on the buttons does nothing (i.e. nothing reloads).
brad wright - #31.1 - 2005-11-18 18:36 -
actually, I figured out that this is a caching problem. If you change the IE cache setting to check for newer versions of stored pages 'every visit to page' rather than the default setting ('automatic'), then everything works fine. I wonder if there is a way to fix this problem...
neko - #32 - 2005-11-12 08:34 -
I found a link to this page on german wikipedia (http://de.wikipedia.org/wiki/AJAX) ...
This introduction is exactly what I was looking for. Although I'm a perl programmer, not PHP, but who cares...? The interesting part is the JavaScript-Side, all other parts are simple (more ore less).
Rishu - #33 - 2005-11-12 17:50 -
Hey there,
Nice li'l piece of code. Am sure it is enough to motivate many of us to start producing our own scriptlets!
Thanks for sharing it with us.
Rishu
Sanket Raut - #34 - 2005-12-02 05:53 -
Why do u think its overhyped, please go and see the wonders done by AJAX in google suggest and gmail.
AJAX is here to stay and belive me most JAVA programmer working on web development would prefer to use AJAX.
SO i guess AJAX is here to stay for a long time
Matt - #35 - 2005-12-03 18:43 -
Thank you.
Nick Toye - #36 - 2005-12-03 21:52 -
Hi,
I can't seem to get this to work. I am trying to learn all this and I am a newbie,
The page is here
http://www.nicktoye.co.uk/Ajax/foo.html
Any ideas why it isn't working?
sergey - #37 - 2005-12-07 14:37 -
excellent. no bullshit, just to the point.
Rajni - #38 - 2005-12-09 18:30 -
Hi,
Can any one tell more link of AJAX...I have listen that many big organizations are going to implement AJAX now...like AceIndiGo as well... http://www.aceindigo.com
AJAX is amazing....
Raj Shekhar - #38.1 - 2005-12-10 06:40 -
Please check the links that the other readers have left, or the trackbacks they have made.
ahmet alp balkan - #39 - 2005-12-09 22:13 -
good! i learnt ajax with this basic script!
thank you rasmus!
Markus Ernst - #41 - 2005-12-17 13:59 -
I was very impressed by Rasmus' tutorial and also by the comments and it motivated me to adapt it for my actual project, where I need support for updating multiple elements. The main difficulty was making sure that the http object is not updated by a following task before it finished the actual one. In return of the inputs I got from this page I want to share the result here:
// Used browser detection method suggested by Dave
function createRequestObject() {
var ro;
if (window.XMLHttpRequest) {
try {
ro = new XMLHttpRequest();
} catch(e) {
ro = false;
}
}
else if (window.ActiveXObject) {
try {
ro = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
ro = false;
}
}
return ro;
}
// Added check if request is busy
var http = createRequestObject();
var busy = false;
// Added array of elements to be updated, and method for populating it
var elementsToUpdate = new Array();
function addElementToUpdate(el_id) {
elementsToUpdate[elementsToUpdate.length] = el_id;
}
// Added method for updating all elements with ids that start with a given string
function updateGroup(prefix, action) {
for (var i=0; i
Markus Ernst - #42 - 2005-12-17 19:51 -
My post seems to have been truncated because of the "less than" character. Feel free to download the script from:
http://www.markusernst.ch/stuff_for_the_world/my_own_ajax.js
Raj Shekhar - #42.1 - 2005-12-18 20:36 -
Thanks. I am not sure why your code does not show up fully in the comments section - maybe it is a restriction that s9y has to prevent spam comments.
Amir Leshem - #43 - 2005-12-21 23:56 -
Atlas and Ajax-based APIs are really hard to maintain, and its client side architecture breaks server-side API.
zumiPage is a better solution.
http://www.zumipage.com
10fotos - #44 - 2005-12-29 03:16 -
I'm going to try it. I have been trying to learn with more complicated examples, but its difficult. I am trying to apply Ajax to one of my favourite sites: 10fotos.com I have been using DHTML till now. But even that I think that it may be bad for crawlers, I want to try and see what happens.
Avi - #45 - 2005-12-29 19:48 -
I am playing around with AJAX on .net.
I have implemented the example and have had not problems, however I am now playing around with a project that is located in a virtual folder outside the Inetpub folder and AJAX is not able to execute the server side function.
Does anyone know how a fix to this problem.
iamtheshadow - #46 - 2005-12-30 16:21 -
Great job man! I was literally up and running in about 2 minutes. Your info made my first steps into AJAX a walk in the park.
THANKS RASMUS!

I'm not sure it can quite be absorbed in 30 seconds as the title claims, but this is the clearest short example of AJAX code I've yet seen. Suddenly it all starts to seem within reach of us mere mortals.
Tracked: Jul 29, 13:11
Tracked: Jul 29, 13:34
Rasmus' 30 second AJAX Tutorial - A wanderer's journal - a breath of fresh air in simplicity. Nice work....
Tracked: Jul 31, 14:09
Tracked: Aug 18, 18:18
Rasmus Lerdorf erklärt AJAX in einem 30 Sekunden Tutorial :-)
Tracked: Aug 18, 21:12
Den Verdacht hatte ich schon länger: Das riesig gehypte AJAX ist eine Luftblase um etwas, was etliche Sites schon ewig machen. Wortreich aufgebläht von hippen Webdesignern, die auch mal im Fernsehn sein wollten. Mangels Interesse hab ich's mir selbst nich
Tracked: Aug 19, 09:03
After taking a look at this tutorial and a couple others, I was dissapointed at the quality of the code so here’s a quick tutorial to get you jump started with AJAX (Asynchronous JavaScript + XML). I am using object...
Tracked: Sep 02, 03:53
Here’s an entry on AJAX. Good dynamic javascript stuff. I’ll have to look at this more when I’m less tired. ...
Tracked: Sep 06, 06:53
Rasmus’ 30 second AJAX Tutorial - A wanderer’s journal ...
Tracked: Sep 06, 07:40
the trackbacks and comments have a wealth of information. Link: Rasmus' 30 second AJAX Tutorial - A wanderer's journal.
Tracked: Sep 06, 15:28
Pour ceux qui ne le connaissent toujours pas Rasmus Lerdorf est le créateur du langage PHP. Et pour celles ou ceux qui entendent parler d'AJAX depuis quelques mois sans savoir comment cela fonctionne ... Ramus vous donne la possibilité de consulter...
Tracked: Sep 06, 22:10
Collected links: Here are some pages which caught my interest this past week, but for which I didn't have enough original content to justify a full entry on this weblog.......
Tracked: Sep 06, 22:34
New Jersey Gas Prices Find cheap gas prices in NJ (tags: nj gas prices) .htaccess tricks and tips Beyond the basics of 404 error pages and blocking access (tags: web reference htaccess) Rasmus' 30 second AJAX Tutorial Another AJ
Tracked: Sep 07, 07:17
Tracked: Sep 07, 15:33
Tracked: Sep 07, 15:35
Tracked: Sep 08, 10:17
Tracked: Sep 08, 10:17
Tracked: Sep 08, 14:03
I agree with almost everyone else, that AJAX is way overhyped. It’s not a language (some job postings now read, “Must be able to program in AJAX.”) Oh well, I was joking with Scott the other day at work about how some fool on the trai...
Tracked: Sep 09, 06:11
AJAX Practical Application The point is, it was understandable, but the “practical application” wasn’t there. You click on a link, and magically a piece of text appears, and walla, you’ve done a little AJAX. Uninspired by that...
Tracked: Sep 19, 05:59
Nein, es handelt sich ausnahmsweise mal nicht um den bekannten Haushaltsreiniger. AJAX ist eine Technik, um Webseiten ohne Zurücksenden zum Browser dynamisch zu gestalten und heisst Asynchronous JavaScript and XML, anderen ist diese Technik vielleicht u
Tracked: Sep 29, 07:22
If ever anyone asks for a simple explanation or example of Ajax, this is the one:
Tracked: Sep 29, 19:31
I just needed a AJAX solution for something I’m developing. With absolutely no prior knowledge in AJAX, I read through this guide, this very guide, in 30 seconds, and managed to get my AJAX stuffs working like charm. Just a quick thank-you to...
Tracked: Oct 03, 17:47
I've been wanting to have a play with AJAX for ages and had book marked Rasmus' 30 second AJAX Tutorial so tonight I took 30 seconds, which turned into 30 minutes and had a play. I've extended his example slightly - to include a javascript fix and to...
Tracked: Oct 11, 07:12
Nein, kein niederländischer Fussballverein, sondern die Abkürzung von "Asynchronous Javascript and XML" - das ist AJAX, eine Methodik zur Kommunikation zwischen (Web-)Server und Client. Heute in der Vorlesung zum ersten Mal gehört, aber es klingt direkt
Tracked: Oct 17, 19:01
Gerade zufällig gefunden: Rasmus’ 30 second AJAX Tutorial. Alles in allem eine knappe Einführung zum Thema AJAX, allerdings ohne die Nutzung irgend einer dicken, fetten Bibliothek. “AJAX von Hand” sozusagen. Sollte ich im Hinterkopf...
Tracked: Oct 25, 16:57
After taking a look at this tutorial and a couple others, I was dissapointed at the quality of the code so here’s a quick tutorial to get you jump started with AJAX (Asynchronous JavaScript + XML). I am using object...
Tracked: Oct 26, 03:06
After taking a look at this tutorial and a couple others, I was dissapointed at the quality of the code so here’s a quick tutorial to get you jump started with AJAX (Asynchronous JavaScript + XML). I am using object...
Tracked: Oct 26, 03:08
Tracked: Nov 15, 16:36
Tracked: Nov 16, 16:05
A very nice and simple Ajax tutorial that illustrates the fundamental concept. This illustrates the most primitive components and also makes clear (IMO) why some additional libraries would be likely to add some value when its time to do something more complicated... Link to Rasmus' 30 second AJAX Tutorial - lunatechian (lunatech-ian)
Tracked: Nov 17, 23:03
Rasmus's simple AJAX tutorial is so straightforward that it should suffice as any web developer's introduction to the technology....
Tracked: Nov 21, 00:49
Rasmus writes “I find a lot of this AJAX stuff a bit of a hype. Lots of people have been using similar things long before it became “AJAX”. And it really isn’t as complicated as a lot of people make it out to be. Here is a s...
Tracked: Nov 26, 02:21
~ The Ten Best Ajax Links: Tutorials, Ex...
Tracked: Nov 28, 10:02
A 30 second tutorial on Ajax by the PHP man himself - Rasmus Lerdorf. I find a lot of this AJAX stuff a bit of a hype. Lots of people have been using similar things long before it became “AJAX”. And it really isn’t as complicated ...
Tracked: Dec 15, 12:15
"I find a lot of this AJAX stuff a bit of a hype. Lots of people have been using similar things long before it became "AJAX". And it really isn't as complicated as a lot of people make it out to be. Here is a simple example from one of my apps."
Tracked: Dec 17, 05:35
So what's actually the idea of this blog? I plan to make this page named Leiseus.net and what you can see here is - as stated above - a progress report of how far I am. So far I'm actually nowhere: just trying to figure out the stuff that I need for this
Tracked: Dec 20, 08:52