Doing it Asynchronously

Filed under Behaviour, Knowledge

Regardless of what you’ve heard about Web 2.0, why it’s cool, why it’s not really 2.0, or why the term Web 2.0 may actually be important, one thing is certain. It’s very shagadellic and it’s all about asyncronicity baby!

Yes that’s right, everyone is doing it asynchronous now, newbies and hackers alike. And why not? It’s all the rage! I mean, how boring was the way your grandparents did it? So mundane, always following the same routine:

  1. Load
  2. Wait for a response
  3. Click
  4. Repeat

Are you really happy with the result of a simple load, wait, click, repeat? Maybe you enjoy the repetitiveness since you’re web site ’seems’ to enjoy it equally, but what if there’s more?. To enjoy the best experience of asyncronicity, all you need are the Ajax twins: XmlHttpRequest and ActiveXObject(”Microsoft.XMLHTTP”) — but that’s where it begins to get a little complicated. It seems these two have been taking over the minds of many a young web developer, corrupting their thoughts with wild imaginative fantasies. Now, day-in and day-out, 24/7, all the web developers can think about is:

  1. Load
  2. Wait for a response
  3. Click
  4. Click
  5. Click
  6. Click
  7. Click
  8. Click
  9. Click

Going with the flow

All these asynchronous communications change the very nature of your application’s flow. You can’t rely on that mundane load, wait, click, repeat cycle because the page never fully loads again, only little pieces of it do. For instance, take this common simple administration tool for a news item list on a website:

Common News Tool

The ‘check mark’ and ‘x’ symbols represent the ‘active’ state of the items in the list.

To ‘activate’ an item, the user would simply click the check box or the x and several things may happen. If you’re using the traditional workflow, your web application will probably do something like this where the page is forced to reload:

Traditional Application Flow

This is a typical “Web 1.0″ application flow. You click, a request is sent to the server, it responds, and the entire page is reloaded to reveal the new change. Often, you’re left sitting at the top of the page and forced to scroll down to even see the change. What fun.

Alternatively, if you’re going asynchronous with Ajax, you’ll end up with something that looks a little more like this, where only small protions of the page change using the appropriate DOM scripting:

Ajax Application Flow

No reloading except for the manipulation of the page with your favorite DOM methods. So where’s the problem? We’ll it’s not really a problem — if you know what you’re doing. The thing you have to remember is that you’re doing things asynchronously now. Requests are going out every time you click the buttons, but they don’t necessarily come back in the same order. Huh? Let me explain with an example. Click this button several times quickly in succession:

Requests

    Notice the order of the requests coming back? The request number represent the order you clicked the button but the order of the list represents the order they were completed by the server. When you click the button, a request is sent to the server and in this case all I’m doing is simulating some server traffic by sleeping the PHP script for a random time:

    <?
    header("Cache-Control: no-cache, must-revalidate");
    sleep( $time = (2/rand(1,8)) );
    echo "$time";
    die();
    ?>
    

    and then sending back the $time before completing the request. If you wait at least 2 seconds between each button click, it’ll probably return requests in the same order because the initial request will complete before the following request. But, if you click it quickly several times quickly in succession, in this case less than 2 seconds apart, you may have a request of 1.5 seconds followed by a request of 0.5 seconds. When that occurs, the second request will finish and complete before the earlier request! This demonstrates asynronous in action - it’s out of sync and out of order, running at the same time as other requests.

    Handling Asynchronous Requests

    If you check out the JavaScript I’m using to do the request it looks something like this:

    var counter=0;
    function doRequest(e){
        var num = ++counter;
        new Ajax.Request("http://jeffreysambells.com/openprojects/PHP/sleeper.php",
        {
            onComplete:function(t){
                e.innerHTML += "<li>Request <strong>" + num + "</strong> <em>(took " + t.responseText + " seconds)</em></li>";
            }
        });
    }
    

    All it does is make an Ajax request (using the Prototype library Ajax object, since it’s already loaded in my blog) and then processes the result when complete. The key thing to remember is that the action you want to take as a result of the request must be placed on the onComplete handler of the Ajax object (or onSuccess in the case of prototype if you’re doing error handling). I often see Ajax rookies doing something similar to:

    var counter=0;
    function doRequest(e){
        var num = ++counter;
        new Ajax.Request("http://jeffreysambells.com/openprojects/PHP/sleeper.php");
        e.innerHTML += "<li>Request <strong>" + num + "</strong> <em>(took " + t.responseText + " seconds)</em></li>";
    }
    

    which is just plain wrong. As I demonstrated earlier, The XmlHttpRequest object is asynchronous, this means that the

    new Ajax.Request("http://jeffreysambells.com/openprojects/PHP/sleeper.php");
    

    line will execute, but may not return before the

    e.innerHTML += "<li>Request <strong>" + num + "</strong> <em>(took " + t.responseText + " seconds)</em></li>";
    

    line executes. If you want your script to wait until the request is complete, you must handle the remaining script from within the onComplete handler by splitting your JavaScript code into objects and methods, then calling the appropriate one when each request is complete.

    In the ‘wrong’ way above, there’s the additional problem of using t.responseText, which isn’t in the scope of the doRequest() function, but we’ll discuss that mistake another time.

    It’s that simple. Nothing too complicated just a complete shift in the ‘top down execution’ approach you’re probably more familiar with. All you have to do is remember that the A in Ajax means Asynchronous. That’s the key.

    If you’d like to learn more about Ajax, I’d suggest first reading the original Ajax article by Jesse James Garrett at Adaptive Path “Ajax: A New Approach to Web Applications” and the many excellent resources over on ajaxian.com but in the mean time have fun with Ajax — the more you do it the better you’ll get.

    12 Comments

    1. Posted December 14, 2006 at 12:34 pm | Permalink

      Excellent article yet again Jeff. I especially love the demonstration aspect of it. Simple and very convincing.

    2. nir tayeb
      Posted December 14, 2006 at 3:50 pm | Permalink

      Great article!

    3. Daniel
      Posted December 14, 2006 at 4:40 pm | Permalink

      Excellent primer!
      But remember to inform the reader that JavaScript could possibly be switched off by the client, so there should be a some redundancy built in (i.e. proper URLs for links and forms). I only say that because I myself forget about that all too often.

    4. Posted December 15, 2006 at 12:57 am | Permalink

      Yes, see related issues with Yahoo, Scriptaculous Libraries

      http://ajaxian.com/archives/autcompletion-issues-with-yahoo-and-scriptaculous-libraries

      http://capxous.com/docs/autcompletion-issues-with-yahoo-scriptaculous-libraries/

    5. Posted December 15, 2006 at 2:30 pm | Permalink

      A great article, one I will refer a lot of people to. I am convincing people of the advantages of Ajax and your article explains the A of ajax.
      Once again, a great article and thanks for sharing it with us…

    6. pete
      Posted December 18, 2006 at 8:49 am | Permalink

      i love this site, the layout is very clean.

    7. gram
      Posted December 19, 2006 at 9:49 am | Permalink

      pretty useless article, actually it doesn’t explains the meaning of A part. The main idea i see is to handle asynchronous responses via callbacks (onComplete prototype handler), but it doesn’t explains main problem:

      first of all, most modern sites are using “synchronous” ajax, that doesn’t means they freeze browser by specifying “synchronous” flag to XMLHttpReuqest, but rather they follow the following steps:
      onSomethingEvent -> Display “Loading” -> Make request |||||| Recieve Response -> Update Interface -> Hide “Loading”.
      That’s what actually make them “SynJAX”, and that’s the problem which must be solved with “A” in AJAX, and not what Jeff writes here.

      second problem, is synchronization of events. If you won’t block user with “Loading” dialog, you should handle concurrent request to the server. Let’s get back to the “check marks” sample in the article. Let’s assume you make really “A”JAX request to the server on each click. If user clicks too much and too often, there is a possibility to get out-of-order requests on the server due to network latency. I.e. your server may receive updated states in the following order: 1: enabled, 3: enabled, 2: disabled. This must be handled carefully, and solutions is not always trivial.
      And that’s the main problem you don’t often see the real part “A” in modern web sites.

    8. Posted December 19, 2006 at 11:31 am | Permalink

      Gram

      regarding:

      most modern sites are using “synchronous� ajax

      and

      you don’t often see the real part “A� in modern web sites

      I would tend to disagree. The power of AJAX is in the fact that you don’t have to force the browser to wait between requests and they can continue asynchronously doing other things while the user waits for an appropriate response. I agree I didn’t mention the synchronous option but but that’s because it’s not the solution to the asynchronous problem, it’s simply an alternative work flow that’s closer to the original page reload option.

      The second problem you mention is what the guts of the article is referring to, as per the clickable example where requests are not necessarily returned in order. I’m not proposing a solution here, only a caution that there is a difference between synchronous and asynchronous and both methods can be used just as effectively, if done properly.

    9. gram
      Posted December 19, 2006 at 12:10 pm | Permalink

      Jeff, i’m glad you here to stand up for your “another ajax-basis” article :) But! Receiving responses in different arbitrary order is not the main problem, because solutions are known and widely used. Autosuggest is a #1 sample of “A”JAX with aync requests coming in different order .
      Main problem, as i said, is properly handling incoming requests on server, and process them in order they were sent, or drop out-of-order ones. Have you seen much of the sites which doesn’t lock you with status message for a moments when you save edited content or settings? No! most of them use SynJAX for simplicity, and especially frameworks makes this problem. ATLAS, for example, will never be AJAX because it heavily uses SynJAX workflow. I bet you better mention these problems and possibly ways to solve them, rather than “another how-to-handle ajax responses with prototype” which takes about half of the whole article text.
      Nothing personal :) Greetz

    10. Posted December 19, 2006 at 12:31 pm | Permalink

      Ah OK, I see you’re point. Perhaps ‘problem’ was the wrong term in the article. My intention was to point out what ‘asynchronous’ means in AJAX, not necessarily to convey all the pros/cons. I have talked to many developers who jump into the whole “Web 2.0″ Ajax thing and don’t even realize what Ajax means let alone that Ajax can be asynchronous. They simply copy-and-paste some arbitrary example from the internet and are then baffled by what happens.

      Thanks for the constructive feedback. I’ll write a follow-up sometime that better explains how to deal with the varying difference in each work flow.

    11. Posted December 19, 2006 at 7:18 pm | Permalink

      “I have talked to many developers who jump into the whole “Web 2.0″ Ajax thing and don’t even realize what Ajax means let alone that Ajax can be asynchronous. They simply copy-and-paste some arbitrary example from the internet and are then baffled by what happens.”

      6 months ago I was one of those developers.

    12. Posted October 21, 2007 at 2:58 pm | Permalink

      they say where to young,to get are self’s sprun. Gautam Asaf.

    4 Trackbacks

    1. By Ajaxian » Doing it Asynchronously on December 14, 2006 at 12:14 pm

      [...] Jeffrey Sambells has written a nice intro post on Doing it Asynchronously. [...]

    2. [...] Doing it Asynchronously: Demonstration and explanation of the A in Ajax. [...]

    3. [...] to make sure that everyone had read Jeff’s excellent article on the ‘A’ in AJAX. Doing it Asynchronously discusses the need to handle the requests to and from your server component properly. Forgetting [...]

    4. By Doing it Asynchronously on January 8, 2007 at 10:18 pm

      [...] Jeffrey Sambells has written a nice intro post on Doing it Asynchronously. [...]

    Post a Comment

    Your email is never published nor shared. Required fields are marked *

    *
    *