Login Register

Hello, Ajax World!

Many programming tutorials contain a "Hello, World!" example, so it seems appropriate to have one for Dojo XHR. In this example, your web page will fetch a snippet of content via XHR and attach it directly to your page.

To setup the example:

  1. Create a file named ajax.txt. It's your decision what to put in the file. "Hello, Ajax world!" is a good start.

  2. Put ajax.txt in the default documents directory on your web server. In many cases, that is the httpdocs directory.

  3. Open your web browser and navigate to the file. You should see the contents of ajax.txt.

  4. Create a file named hello.html. Copy and paste the contents of Example 1, “Hello, Ajax world!” into that file.

  5. Set the URL argument to the value you used to test the server setup.

  6. Put hello.html in the default documents directory on your web server. In many cases, this is the httpdocs directory.

    Put the file in the same directory as ajax.txt.

  7. Make the file read-only.

  8. Open your web browser and navigate to hello.html. You should see the contents of ajax.txt in your browser window.

Example 1. Hello, Ajax world!

<html>
 <head>
  <title>Hello, Ajax world!</title>
  <script type="text/javascript"
    src="http://o.aolcdn.com/dojo/1.0.0/dojo/dojo.xd.js"></script> <!---->
  <script type="text/javascript">
    function hello() { // 
      dojo.xhrGet( { // 
        // The following URL must match that used to test the server.
        url: "http://server/ajax.txt", 
        handleAs: "text",

        timeout: 5000, // Time in milliseconds

        // The LOAD function will be called on a successful response.
        load: function(response, ioArgs) { // 
          dojo.byId("cargo").innerHTML = response; // 
          return response; // 
        },

        // The ERROR function will be called in an error case.
        error: function(response, ioArgs) { // 
          console.error("HTTP status code: ", ioArgs.xhr.status); // 
          return response; // 
          }
        });
      }
  </script>
  <script type="text/javascript">
    dojo.addOnLoad(hello); // 
  </script>
 </head>
 <body>
   <div id="cargo" style="font-size: big"></div> <!---->
 </body>
</html>

This JavaScript program bootstraps Dojo 1.0 via the AOL Content Distribution Network. If you choose to install Dojo locally, use the following script tag to bootstrap Dojo:

<script type="text/javascript" src="dojo/dojo.js"></script>

Modify the directory reference in the SRC attribute to match the location of your Dojo installation

This function will be called after Dojo completes its initialization phase.
The desired HTTP method call (GET, POST, PUT, DELETE) is part of the function name.
Inside this function, the this variable will be the object used as the argument to the dojo.xhrGet() call.
This statement demonstrates one way of stuffing a server response into a document. The dojo.xhrGet call asks Dojo to treat data from the server as text (handleAs: "text"). Therefore response will be a text string.

Dojo recommends that you always return(response); to propagate the response to other callback handlers. Otherwise, the error callbacks may be called in the success case.

ioArgs is an object with some useful properties on it. For instance, for XMLHttpRequest calls, ioArgs.xhr is the XMLHttpRequest that was used for the call.

The Dojo team recommends that you always use dojo.addOnLoad() to call any startup code you write. Even for this simple example, unless we use dojo.addOnLoad(), we cannot reliably assume that the main function hello() will run after Dojo initialization completes.

Use dojo.addOnLoad() only to run start-up code. Do not use dojo.addOnLoad() to call JavaScript event handlers.

Two ways to abuse Dojo. The following techniques will produce tedious, head-scratching debugging sessions by not using dojo.addOnLoad().

<body onload='hello'>
This technique is never a good idea when using Dojo. You have no assurance that hello() will run after Dojo initialization.
Put the hello() body in a <script> without dojo.addOnLoad()
This technique usually fails with Dojo. Only the simplest JavaScript programs, like "Hello, Ajax world!" can employ this technique. It's a safe bet that yours isn't one of them.
Holding area for the server response. A common use case is that the server returns an HTML fragment that the client will want to display. The innerHTML attribute of such placeholder <div> tags is a convenient way to display HTML fragments.

Needs updating to 1.0

This example needs to be updated to 1.0, and may want to consider to update to include proper required options.

Using a direct connection to the non-base dojo.js file breaks consistency with the rest of the book and breaks the mantra of "use requires" that is seen elsewhere.

An area may want to be added to this about handling caching etc through "preventCache" etc.

no require necessaray

This example is entirely correct, and it does pull in the base dojo.js which includes the dojo.xhr* functions built right in. I will update the URL for 1.0, though.

Regards

Avoid making orphan widgets by destroying them

If you have any widgets in your node you will make them orphans when doing this:

dojo.byId("cargo").innerHTML = response;

You should destroy any widgets existing in the node prior to changing the innerHTML. You can go about this in two different ways:

  1. Use a dijit.layout.ContentPane for all your data and call setContent() that takes care of this problem
  2. Use the following function when you change the innerHTML
    function setInnerHTML (content, dom_node)
    {
    	dojo.query('[widgetId]', dom_node).forEach(function(n) {
    		dijit.byNode(n).destroy();
    	});
    	dom_node.innerHTML = content;
    	dojo.parser.parse(dom_node);
    }

This becomes a problem if you for instance have a form with dojo.form elements since the parser will complain that your dijit already exists in the registry the second time you load the same form.