lunatechian (lunatech-ian)

one relating to, belonging to, or resembling lunatech

Rasmus' 30 second AJAX Tutorial

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");
        ro = new XMLHttpRequest();
    return ro;

var http = createRequestObject();

function sndReq(action) {'get', 'rpc.php?action='+action);
    http.onreadystatechange = handleResponse;

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";

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">

Once you click on that link, that will dynamically be changed to:

  <div id="foo">
  foo done

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) {'get', 'rpc.php?action='+action+'&arg='+arg);
    http.onreadystatechange = handleResponse;

And your handleResponse can easily be expanded to do much more
interesting things than just replacing the contents of a div.


Update: Disallowed comments on the entry

Defined tags for this entry:


Trackback specific URI for this entryTrackback URL
  1. Demystifying AJAX
  2. Get started with AJAX in 30 seconds
  3. 30 second AJAX Tutoria
  4. State of Ajax: Progress, Challenges, and Implications for SOAs
  5. AJAX in 30 Sekunden
  6. Hosen runter, AJAX!
  7. AJAX: Instant Tutorial
  8. AJAX. woot
  9. Tutorial d&#8217;AJAX en 30 segons
  10. Rasmus' 30 second AJAX Tutorial - A wanderer's journal
  11. Rasmus' 30 second AJAX Tutorial
  12. Collected links
  13. links for 2005-09-07
  14. [Tutorial] Apprendre AJAX en 30 secondes ?
  15. [Tutorial] Apprendre AJAX en 30 secondes ?
  16. Thinking about AJAX
  17. Thinking about AJAX
  18. The 30 Second AJAX Tutorial
  19. Link: 30 second AJAX tutorial
  20. Styling &#8220;Simple&#8221; AJAX
  21. AJAX in 30 Sekunden
  22. Rasmus' 30 second AJAX Tutorial
  23. AJAX in 30 seconds
  24. AJAX - finally!
  25. Ajax
  26. AJAX in 30 Sekunden
  27. AJAX: Instant Tutorial
  28. AJAX: Instant Tutorial
  29. The Ten Best Ajax Links: Tutorials, Examples, and History
  30. Top Ten AJAX Links
  31. Rasmus' 30 second AJAX Tutorial - lunatechian (lunatech-ian)
  32. A Concise AJAX Tutorial
  33. 30 second AJAX Tutorial
  34. The Ten Best Ajax Links: Tutorials, Examples, and History
  35. Rasmus&#8217; 30 second AJAX Tutorial - lunatechian (lunatech-ian)
  36. Rasmus' 30 second AJAX Tutorial
  37. The next day...


    • Posted bySumeet
    • on
    Nice. Rasmus rocks!
  1. Definately. Reading his mails on the php-general mailing list always makes go "aha! that is cool/simple"
    • Posted bygregor-e
    • on
    Awesome explanation. You could do a whole book of these and make a mint!
  2. Rasmus has a book "Programming PHP" by o'reilly publishers. I have not read it, but I can guess it would be good.
    • Posted byFin
    • on
    Thank you for this. The multiple parameter part is exactly what I was trying to figure out!
    • Posted byJacques
    • on
    Nothing like to know the things! :-) I try implemate this with a PEAR QuickForm setDefaults method to fill a field on the tab...
    • Posted bychuck
    • on
    can you recomend a good lightweight javascript xml parser that works on all major browsers?

  3. 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 :-) .
  4. 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.
    • Posted bydave
    • on
    oh, this is so pretty! it's exactly what I was looking for, thanks!
    • Posted byJonas Geiregat
    • on
    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 ...
    • Posted byDave
    • on
    • Posted byScott Pobiner
    • on
    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?

  5. 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
    • Posted byYeJun Su
    • on
    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 :-)
    • Posted byJeff
    • on
    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"
  6. Just for you:

    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.

    • Posted byJohn
    • on
    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.
    • Posted byNathan
    • on
    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
    • Posted byAnonymous
    • on
    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):
    • Posted byRichard
    • on
    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.
    • Posted bywtanaka
    • on
    The important part about the hype is that people are using it, which will make it more stable and standard.
    • Posted byNader
    • on
    A couple of months after your enlighting post about AJAX we have finally used the technology to boost our project . It works! ;-)

    Thanks again, keep up the great posts on your blog, Nader
  7. 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?
    • Posted byJeff Garbers
    • on
    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;
    • Posted byJeff Garbers
    • on
    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?
    • Posted bySteve B.
    • on
    Jeff - good question. I had the same issue. I changed the get line to:'GET', 'process.asp?rnd=' + Math.random()*4 +'action='+action);

    Works great! Take care,
    • Posted byJeff Garbers
    • on
    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!
    • Posted byPhilB
    • on
    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 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
    • Posted byDave
    • on
    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".
  8. 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
    • Posted byPiotr
    • on
    I don't know javascript but it seems to me that

    if(response.indexOf('|' != -1))

    should be

    if(response.indexOf('|') != -1)
    • Posted bySteven
    • on
    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.
    • Posted byOlli
    • on
    See or at his web site

    • Posted byJoe
    • on
    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.
    • Posted bySumit
    • on
    Wonderful (*Article*) -- (*Really Great, Superb*), Never New Ajax wud be so easy to start...!! :-)
    • Posted byworas
    • on
    It's great work! Thanks a lot!
    • Posted bycannibal
    • on
    • Posted byAnonymous
    • on
    The best tutorial to start with AJAX, thx for that
    • Posted byDerf
    • on
    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.
    • Posted bytripdragon
    • on
    Please forgive me, but how can this load in something more? Like a web page or tags of code ?

    fish Mysterious as an example ?
    • Posted byAlan Jacobs
    • on
    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);
    alert(xmlhttp.responseText ); // Ok!!
    alert(xmlhttp.responseXML.getElementsByTagName('*').length); // Zero :-((

    Any idea why?

    • Posted byygor
    • on
    Great example. Thanks.
    • Posted bybrad wright
    • on
    This code doesn't seem to work with IE. I created a simple web app based on this code:

    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).
    • Posted bybrad wright
    • on
    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...
    • Posted byneko
    • on
    I found a link to this page on german wikipedia ( ...

    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).
    • Posted byRishu
    • on
    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.

    • Posted bySanket Raut
    • on
    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
    • Posted byMatt
    • on
    Thank you.
    • Posted byNick Toye
    • on

    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

    Any ideas why it isn't working?
    • Posted bysergey
    • on
    excellent. no bullshit, just to the point.
    • Posted byRajni
    • on

    Can any one tell more link of AJAX...I have listen that many big organizations are going to implement AJAX AceIndiGo as well...
    AJAX is amazing....
  9. Please check the links that the other readers have left, or the trackbacks they have made.
  10. good! i learnt ajax with this basic script!

    thank you rasmus!
    • Posted byNSJ
    • on
    Nice tutorial dude. It helped me a lot
  11. 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
  12. My post seems to have been truncated because of the "less than" character. Feel free to download the script from:
  13. 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.
  14. Atlas and Ajax-based APIs are really hard to maintain, and its client side architecture breaks server-side API.
    zumiPage is a better solution.
    • Posted by10fotos
    • on
    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: 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.
    • Posted byAvi
    • on
    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.
  15. 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.