Slashdot Mirror


Asynchronous Requests with JavaScript and Ajax

An anonymous reader writes "I rarely read an entire article about a single object, especially one that is this simple. However, you will use this object over and over again in each page and application that you write that uses Ajax. This article shows you how to create XMLHttpRequest instances in a cross-browser way, construct and send requests, and respond to the server."

18 of 178 comments (clear)

  1. If you like this, try too AJAX Developer's Journal by jg21 · · Score: 4, Informative

    If you liked this article then you will surely like AJAX Developer's Journal , just launched digitally/online and replete with how-to articles and interviews, all freely available. It's edited by Rob Gonda.

  2. Yeah, new news indeed by masklinn · · Score: 4, Informative

    I mean, the first articles explaining how to create cross-browsers XMLHTTP requests ain't have more than a pair of years anyway...

    Wouldn't it be slightly more interresting if Slashdot promoted useful stuff such as the Dojo or Mochikit Javascript libraries/toolkits (others exist btw, those are just fairly stable and advanced), which actually:

    • Make that kind of stuff easier
    • Make that kind of stuff more reliable
    • Give great tools/shortcuts for working with javascript
    • Actually work

    Just wondering...

    --
    "The way we can tell it's C# instead of Haskell is because it's nine lines instead of two." -- wadler
    1. Re:Yeah, new news indeed by ChrisZermatt · · Score: 4, Informative

      Better yet, QooxDoo. Best I come across so far, even though its still in its early stages...
      http://qooxdoo.oss.schlund.de/

  3. Re:IBM articles; Security with Javascript by secondsun · · Score: 1, Informative

    I work for a company that makes a virtual office web-app. We log some interesting statistics about the end users.

    1% don't use IE, and all have javascript enabled.

    So no, we have not run into the problem with people having javascript disabled.

    --
    There is nothing wrong with being gay. It's getting caught where the trouble lies.
  4. Re:And who invented the XMLHttpRequest class ? by Anonymous Coward · · Score: 1, Informative
    The company that never invents anything did. And have been using it for years before it was hyped as ajax and web 2.0.

    btw. Funny seeing IBM criticizing the people who invented the damn thing in the first place of implementing it differently than others have chosen to reimplement it.

  5. What to do with XML results? by ccady · · Score: 4, Informative

    Bah. That's easy. The business of creating and using an XMLHttpRequest is well-documented and easy to do. What is far less well documented is how to access the resulting XML as a cross-browser XML DOM object. (Accessing it as text is easy.)

    How does one access the results 1) as an XML DOM, and 2) in a cross browser way. I am currently investigating Sarissa.

    I challenge someone to come up with a good article on that!

    --
    J'aime mieux les méchants que les imbéciles, parce qu'ils se reposent. -- Alexandre Dumas
  6. Easier than the article by esconsult1 · · Score: 4, Informative
    Just use the excellent prototype javascript library instead. Saves a ton of time. It's cross platform, dev language agnostic, and has super sweet functionality built in.

    I guess you can use JSON, and XML data formats with prototype, but I just use plain old text to accomplish whatever I want.

    Prototype is also used in Ruby on Rails and its PHP analogue CAKE, and also the excellent perl framework Catalyst

  7. Sarissa tutorial by Spy+der+Mann · · Score: 2, Informative
  8. Re:IBM articles; Security with Javascript by Kjella · · Score: 2, Informative

    I work for a company that makes a virtual office web-app. We log some interesting statistics about the end users.

    1% don't use IE, and all have javascript enabled.

    So no, we have not run into the problem with people having javascript disabled.


    You left out the most important detail - does your site require IE/Javascript? Because if I heard about your service, here's what I usually do:

    1. Read article, which is usually regurgitated press material
    2. Google for user experiences or reviews
    3. See that your app requires IE and move on

    --
    Live today, because you never know what tomorrow brings
  9. overriding the constructor by ydnar · · Score: 5, Informative

    With JavaScript, the object that is returned by the newoperator is the return value of the constructor. Which means you can set/override pretty much any object/property with a pseudo-constructor that returns any arbitrary object (class).

    Adding XMLHttpRequest to Internet Explorer:

    if( typeof window.XMLHttpRequest == "undefined" ) {
        window.XMLHttpRequest = function() {
            var types = [
                "Microsoft.XMLHTTP",
                "MSXML2.XMLHTTP.5.0",
                "MSXML2.XMLHTTP.4.0",
                "MSXML2.XMLHTTP.3.0",
                "MSXML2.XMLHTTP"
            ];

            for( var i = 0; i < types.length; i++ ) {
                try {
                    return new ActiveXObject( types[ i ] );
                } catch( e ) {}
            }

            return undefined;
        }
    }

    y

  10. try AFLAX? by MORTAR_COMBAT! · · Score: 2, Informative

    http://www.aflax.org/

    poke around in those (excellent) libraries a bit, maybe you'll find more basic socket handling facilities that you are looking for.

    maybe "web 3.0" is closer than we think. servers pushing data to web clients.

    --
    MORTAR COMBAT!
  11. No Thanks to AJAX Developer's Journal by Anonymous Coward · · Score: 1, Informative
    What does ethics have anything to do with professional reporting and journalism?
    -- Fuat Kircaali, CEO of Sys-Con Media, publisher of several computer magazines

    Yet another one of Sys-Con's online publications people should avoid for various reasons.

  12. Firefox AJAX Debugger by Val314 · · Score: 4, Informative

    pretty usefull: https://addons.mozilla.org/extensions/moreinfo.php ?id=1843&application=firefox

    "FireBug is a new tool that aids with debugging Javascript, DHTML, and Ajax. It is like a combination of the Javascript Console, DOM Inspector, and a command line Javascript interpreter."

    thanks http://weblogs.mozillazine.org/gerv/archives/2006/ 01/firebug.html for the tipp

  13. For those that missed it... by ZeldorBlat · · Score: 2, Informative

    This is the follow up article to the one posted a month or two ago:

    http://developers.slashdot.org/article.pl?sid=05/1 2/11/2327239

  14. Re:Ajax is OLD, web 2.0 - please.... by GeekLord · · Score: 2, Informative

    Although very simples, AJAX represent a very important step: its the first ever functionality that actually allows a web page to function more like a traditional app. But we only took the first steps. It took YEARS for us to realize what the hell an asynchronous request represented, and when we finally did, most of people waited to see it implemented on a more usabe fashion. This is where the multiple libraries enter.

    Here is a nice start: someone already posted this, but here it goes again: http://en.wikipedia.org/wiki/AJAX

    Now, web 2.0 is not about changing what the web represents, that much is already established. The web 2.0 is about improving usability and response time, an when properly implemented, ajax can improve those factors by an order of magnitude. Well, I dont know about you, but where I came from, a ten fold is always a revolution.

    So stop whining and help us make the web a better one!

  15. The Irony... The Irony... by Baldrson · · Score: 2, Informative
    From the TIBET(tm) writeup on "AJAX":

    Ironically, the real value in XMLHTTPRequest isn't that communication can be asynchronous. Form submissions, the previous way of handling server communication, were and still are asynchronous. XMLHTTPRequest actually makes it possible to support _synchronous_ calls and provides a single unified way to make either type of call.

    Most writings on AJAX would have you believe that's enough -- make an asynchronous call, get an AJAX application. Unfortunately, as anyone who's done much programming with asychronous calls (aka threads) can tell you, making the call is the easy part -- it's coordinating the results that's hard. A simple real world example highlights "the sync problem".

    The Sync Problem

    Its a common client-side requirement to fetch a template containing static data along with dynamic data from a web service call, blend them into a single UI element, and then display that element in a portion of the user's currently displayed page. In this common case you've got two separate data sources meaning you have two separate calls whose results have to be blended only after both complete. When confronted with this reality most developers switch to making synchronous calls (taking advantage of XMLHTTPRequest's truly new feature to "cheat"). If you decide to hang in there and stay with the asynchronous call format that's great, but we've yet to see a single AJAX toolkit that offers you any kind of multiple-request coordination -- so you'll end up writing the synchronization logic yourself.

    If you use TIBET its simple:

    // set up two requests to make the async calls (you can have more if you like)
    request1 = ServiceRequest.create(dc('async',true,'other','par ameters'));
    request2 = ServiceRequest.create(dc('async',true,'some','para meters'));

    // create a function to observe the completion signal we'll be sending below
    response = function(aSignal) { alert('The requests are done'); };

    // create an "And Join" saying both need to complete (TIBET also supports "Or Joins")
    join = TPAndJoin.create('AllDone');
    join.addObservation(request1);
    join.addObservation(request2);

    // tell our response function to observe the signal our join will send
    response.observe(join, 'AllDone')

    // activate the requests...TIBET handles the rest
    request1.activate();
    request2.activate();
    Since TIBET was built before you could "cheat" via XMLHTTPRequest it's been designed to support asychronous event coordination from the start. TIBET uses event signaling and a set of types based on the Workflow Management Coalition's petri-net models for workflow event coordination to handle event synchronization. Because it uses events rather than XMLHTTPRequest callbacks you can use the previous example's pattern to join responses from both the server and the user since interactions with the user are asynchronous as well.
  16. AJA? by roman_mir · · Score: 2, Informative
    Before there was a word AJAX, there was a way to do the same thing, and I had to do it too: hidden frames + javascript. It wasn't XML though.

    Just last Friday I had to use AJAX but without XML at work. Instead of XML, it is much easier to just do this:

    [["key1","value1"],["key2","value2"],["key3","valu e3"],["key4","value4"]] - send this string as response and then in your javascript simply eval it. It will become a 2 dimensional array. If you want, you can unroll the array into a hashmap:
    var arr = eval(strin);
    var map=new Array(arr.length);
    for(var i=0;i<arr.length;i++) {
      map[arr[i][0]]=arr[i][1];
    }
    now you can access values in the map by the associated keys:
    map["key4"] == "value4"