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

36 of 178 comments (clear)

  1. Hello world by jcaldwel · · Score: 3, Insightful

    This looks like the same AJAX "Hello World" I have read dozens of times before. Nothing new here.

    1. Re:Hello world by KiloByte · · Score: 2, Interesting

      Actually, I thought they mean a way how to have it truly asynchronous -- ie, without building a whole TCP connection first, getting acks and what not. But no, this is just the very basic XMLHttpRequest.

      So, would anyone be able to tell me how to send something to a server using a single half-trip? It may be a part of a persistent connection, any eventual ack can be sent through a separate channel, I don't really care about bandwidth -- all that matters is the latency between the user's action and the time server receives the command. Think "interactive app", where interaction means something faster than a matter of seconds.

      The only way I can think of so far is trying to send dummy requests to command.1.is.foo.dns.my.server and have the DNS relay me these; however, this would be an insanely ugly hack. Any better ideas?

      --
      The creatures outside looked from Alt-Right to Antifa; but already it was impossible to say which was which.
    2. Re:Hello world by mrchaotica · · Score: 2, Interesting

      Quick question for you: If you only need a "half-trip," how could latency possibly matter? Since it's not waiting for a response from the server, there's no way the client could possibly know how long the request took!

      If you throw away a can, does it matter how long it takes to get to the recycling center?

      --

      "[Regarding the 'cloud,'] ownership was what made America different than Russia." -- Woz

    3. Re:Hello world by Bogtha · · Score: 2, Insightful

      You can't be looking very carefully then. Practically all the Ajax tutorials I've seen make beginner mistakes. This one's special because it's actually decent code.

      --
      Bogtha Bogtha Bogtha
  2. 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.

  3. IBM articles; Security with Javascript by WebHostingGuy · · Score: 2, Interesting

    While slightly off-topic, I do have to say that IBM's articles are some of the best on the net. They have very good writers and can explain things without resorting to techno-babble for the layman.

    On another note, it seems that the current flavor of the month is Ajax. However, this requires that javascript be enabled. Is anyone running into the problem of finding a lot of users are forgoing this technology because they have (or have been told by their company) to disable javascript for security concerns?

    --
    Quality Hosting e3 Servers
    1. Re:IBM articles; Security with Javascript by masklinn · · Score: 4, Interesting

      I usually consider that 10% of the users have javascript partially or fully disabled either because they use javascript-less browsers (rare) or because of security issues (corporate environments). The trick there is to develop your web application with the Progressive Enhancements philosophy in mind: build a layered, Javascript/AJAX is merely a client-side behavioural layer added on top of the content layer (pure HTML) and the style layer (CSS), it relies on both but shouldn't be necessary for the application itself to work. It's merely applying the good ol' layers separation on your client-side web pages.

      Following the Progressive Enhancements "way" raises the chances that your websites will degrade fairly gracefully when the upper layers are not available (old browser, quirks, ...) without "shutting down" the whole site for the user (or lower the cost/pain of having them degrade gracefully).

      --
      "The way we can tell it's C# instead of Haskell is because it's nine lines instead of two." -- wadler
    2. 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
    3. Re:IBM articles; Security with Javascript by Jasin+Natael · · Score: 5, Insightful
      Well, graceful degradation is nice, but...

      I think users who are disabling JavaScript are already doing themselves more harm than good. There are some genuinely good dynamic interfaces out there, and compared to the time and bandwidth savings they'll get by using them properly, the time required to install FireFox or a popup/ad blocker is negligible.

      At least for intranet and company sites, there's a genuine demand for functionality that it's impossible to expose without full Javascript support. Consider a drag-and-drop interface where customer orders appear on the left-hand side, and the line items can be organized into a grid of dates and production stations (a piece of machinery or a particular set of workers) via drag-and-drop. I have a working AJAX app that does this, but I can't think how such an application would be useful in the absence of JavaScript. It would require literally hundreds of pageloads and a metric ton of typing (remember: No Javascript = No Calendar Picker) to do any meaningful analysis and manipulation, and the very act of using it would destroy the user's workflow/concentration, rendering the application less useful than the scrawled paper notes it replaces.

      This is the direction the web is moving. There are a lot of consumer applications that would benefit from taking a more dynamic approach, especially when you combine the intuitiveness of drag and drop with the live feedback made possible by XMLHTTPRequest. I think that coddling to users without JavaScript is holding them back, as well as creating a lot of useless "busy-work" for web designers and developers.

      Jasin Natael
      --
      True science means that when you re-evaluate the evidence, you re-evaluate your faith.
    4. Re:IBM articles; Security with Javascript by phlamingo · · Score: 2, Insightful
      ... a genuine demand for functionality that it's impossible to expose without full Javascript support ...

      If only this were true ...

      The internal corporate sites I'm used have a pretty good chance of running only with I-stinking-E, using whatever demon-inspired lock-in technologies they are teaching to Microsoft "programmers" these days.

      It really twists my guts in a knot. Then, I smile, and do what I have to to get the job done.

      --
      I had forgotten how much cooler teenagers look when they are smoking. Oh, wait ...
  4. Ajax is OLD, web 2.0 - please.... by chrisdrop · · Score: 2, Insightful

    I am sorry - i cannot believe how much hype there is over 'ajax'. This is something that has been going on for so long. In the past - we have done this using 1x1 frames and parsed the Xml with light Js libraries. I guess I must be getting old - I always sneered at the 'mainframers' that would complain and say 'that is nothing new - we have been doing that since 1876'. Now - I guess I see the same thing. A new marketing hype name - and the old technique is here

    I hope that the next version of the web is much more than HTML pages that don't refresh with a full round trip. Really though - we did this at least 5 or 6 years ago..... I like google maps, Flickr and the others, but it is NOT a revolution. Someone innovate for real and show me a revolution if you want to justify the Ajax hype or the Web 2.0 hype!!!!

    -Irate -
    Chris

    --
    " I have no tag line. "
    1. Re:Ajax is OLD, web 2.0 - please.... by dbucowboy · · Score: 2, Insightful

      It's not about the technology as much as the innovative ways it is being implamented.

      --
      This just in! 3 out of 4 people make up 75% of the population.
    2. 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!

  5. 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/

  6. Funny title by Jugalator · · Score: 4, Funny

    OK, here goes some /. nitpicking but it was a funny title: Asynchronous Requests with JavaScript and Ajax. Someone need a reminder of what Ajax is again (Asynchronous JavaScript And XML).

    --
    Beware: In C++, your friends can see your privates!
    1. Re:Funny title by Xugumad · · Score: 4, Funny

      Ah, so what you're saying is the title should have been "Asynchronous Requests for XML with Javascript and Ajax"? :)

    2. Re:Funny title by volve · · Score: 2, Funny

      Next you'll be saying that there's no such thing as an "ATM Machine" or a "PIN Number". The's unpossible!

      Damn commies.

      -volve

  7. 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
    1. Re:What to do with XML results? by bahwi · · Score: 4, Insightful

      Use AJAX without the X. JSON works quite well when XML is overkill. Sometimes you will need the complexity of XML, but much of the time(including those examples in that article), XML is complete overkill.

  8. 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

  9. Re:If you like this, try too AJAX Developer's Jour by kurth · · Score: 3, Interesting

    My honest first impression was that ti was a spyware site, you know, the ones that look useful, but are really just there for the sake of serving ads?

  10. Sarissa tutorial by Spy+der+Mann · · Score: 2, Informative
  11. Re:If you like this, try too AJAX Developer's Jour by Mike+Savior · · Score: 2

    By all means a pretty site does not mean a good site, there's obviously great content you can find on minimalistic or ass-ugly pages- but is it just me or does for a site preaching the benefits of ajax, it's really disgusting-looking?

    --
    space is pretty cool.
  12. Re:XML isn't really needed. by ankhcraft · · Score: 2, Insightful

    Okay, I have to reply, because now you're just rewording part of my statement in lieu of a useful reply.

    I just _said_ that the XML isn't useful _unless_ you need/want communication with 3rd-party components that use XML.

    Plus, you also seem to be hinting that one should always aspire to connect their app up to 3rd-party components or even that one should always do the work to make the app integratable w/ XML before even knowing that this is necessary or required.

    I'm sorry, but this is just another example of wasted programming hours and wasted money spent on the same. If the app does not need it, nobody has asked for it, and suggestions to the contrary are not agreed with, don't build it.

    --
    ...
  13. 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

  14. Re:If you like this, try too AJAX Developer's Jour by Parham · · Score: 2, Insightful

    It took me less than 50 milliseconds to realize that site wasn't good... it's full of advertisements and there is little teaching going on. If I visited an AJAX-resource website, I'd like to see some code as soon as possible.

  15. 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!
  16. 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

  17. 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

  18. Re:XML isn't really needed. by DogDude · · Score: 2

    There aren't too many websites that make sense to act as service providers. Most websites are simply just informational, or shopping carts. I provide our products data to all of the major search engines/shopping sites, but each interface is completely different. This idea of some kind of universal XML has *never* paid off, and I can't imagine it ever will. I agree with the parent poster... it's a lot of waste, both in programming cycles, and machine cycles/bandwidth to add in a layer that is unnecesary.

    That being said, I've been using XMLHTTPRequest for many years for some internal stuff. No actual XML anywhere on the site, though. If I did waste my time adding in "XML", my app would be significantly slower.

    --
    I don't respond to AC's.
  19. 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.
  20. If you dont understand all of this.... by hayriye · · Score: 2, Insightful
    * open(): Sets up a new request to a server.
    * send(): Sends a request to a server.
    * abort(): Bails out of the current request.
    * readyState: Provides the current HTML ready state.
    * responseText: The text that the server sends back to respond to a request.

    Don't worry if you don't understand all of this (or any of this for that matter)

    I think everybody understand all of this, if somehow involved with software development.

    This article is useless like 90% of the DeveloperWorks articles.

  21. Well THAT skews your results. by Andy+Dodd · · Score: 2, Insightful

    If your app requires JavaScript, then clearly, anyone who is logged as using your app WILL have JavaScript enabled.

    Your logs won't show how many people wanted to use your app but didn't because they had JS turned off for whatever reason.

    --
    retrorocket.o not found, launch anyway?
  22. Ugh by kuzb · · Score: 2, Insightful

    They lost me as soon as I saw "Web 2.0" in large bold letters. For once, can we keep the marketing BS out of techincal articles? They're like sandpaper down the side of my face.

    --
    BeauHD. Worst editor since kdawson.
  23. 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"