Try an online Ajax class for free!
Additional Resources

Ajax Frameworks

In this lesson of the Ajax tutorial, you will learn...
  1. About the benefits of Ajax Frameworks.
  2. How to use the Dojo framework to make XMLHttpRequests.
  3. How to use the Prototype framework to make XMLHttpRequests.
  4. About some other popular frameworks.

The Purpose of Frameworks

JavaScript frameworks can serve several purposes:

  • Abstraction. Writing JavaScript is notoriously difficult in large part because of the browser and platform differences. Although this has improved a lot since the Netscape 4 / IE 4 days, JavaScript developers still have to be aware of differences in browser object models. One purpose of frameworks is to abstract those differences.
  • Widget Libraries. Many frameworks provide libraries of pre-written, customizable widgets (expandable trees, accordions, autocompletes, drag-and-drop controls, etc.).
  • Development Structure. Some frameworks make it easier to create structured, object-oriented Ajax applications.

Choosing a Framework

Choosing a framework to use for your Ajax applications is a difficult task. At the time of this writing, the AjaxPatterns website (http://ajaxpatterns.org/Ajax_Frameworks) listed:

  • 30 multi-purpose Ajax frameworks
  • 32 Java-specific Ajax frameworks
  • 27 PHP-specific Ajax frameworks
  • 15 .NET-specific Ajax frameworks

Many of these frameworks are created by individuals or small groups and most are non-commercial. So how do you choose? It's a tough job, but here are some general guidelines.

  1. Choose a framework with staying power. The more mature frameworks like Prototype and Dojo, which we will review shortly, have built up pretty large followings, so they are more likely to persist. They are also more likely to be better documented and supported by an online community.
  2. Choose a framework that is either language neutral or specific to your server-side language. This is pretty obvious, but you don't want a PHP framework if you are building a Java application.
  3. Choose a framework that plays nicely with other frameworks. For example, script.aculo.us (see footnote) and Rico (see footnote) both require Prototype, so if you want to use some of their cool dynamic features, you will have to use Prototype as well.
  4. Choose a framework that fits your skillset. If your developers are very comfortable with JavaScript, you might choose a framework that is JavaScript-centric like Prototype or Dojo. If you are a team of Java or JSP developers who have not done much client-side programming, you might choose a framework like AjaxAnywhere (see footnote), which autogenerates the JavaScript. Such frameworks provide less flexibility but may decrease development time.

We will look at two popular frameworks: Dojo and Prototype. Note that these frameworks have a much broader focus than Ajax, but for now, we'll be focusing on how they handle XMLHttpRequests.

Dojo (see footnote)

Dojo is a multi-purpose JavaScript toolkit that, according to its website, "allows you to easily build dynamic capabilities into web pages and any other environment that supports JavaScript sanely." Dojo has been in development since late 2004 and is one of the most comprehensive JavaScript toolkits available. It is client-side specific so it can be used on any platform with any server-side language. The documentation for Dojo is relatively good compared with other frameworks.

Downloading Dojo

The latest version of Dojo is freely available for download at http://dojotoolkit.org/downloads as an archived file. Simply extract the files to a folder on your web server. (see footnote) Version 1.1 of Dojo is included with your class files (/dojo/dojo.js). Note that dojo.js has several dependencies, so you should leave the file structure intact.

To make the Dojo toolkit available, include the dojo.js file as you would any other JavaScript library:

<script language="javascript" src="dojo/dojo.js"></script>

You can also use AOL's Content Distribution Network (CDN) for Dojo. This may make your web page download faster as it's possible the user has visited another site that used AOL's CDN and already has the Dojo files cached.

<script type="text/javascript" src="http://o.aolcdn.com/dojo/1.1.0/dojo/dojo.xd.js"></script>

Our class files use this CDN. If you do not have an internet connection, you need to change the path in the script tag to dojo/dojo.js.

Using Dojo for Ajax

Older Dojo versions including .3 and .4 use the dojo.io.bind object to provide a wrapper around the XMLHttpRequest (XHR) object.  The 1.x release of Dojo provides a different function and no longer provides dojo.io.bind.  The new version of Dojo provides two functions that expose XHR a little more directly, dojo.xhrGet and dojo.xhrPost.

Both XHR wrapper functions take a single object as an argument. The only difference between them is the HTTP message type used for the XHR object; dojo.xhrGet will cause the XML request to use the HTTP GET type while dojo.xhrPost will use the HTTP POST message type.

Since both of these functions are part of Dojo base they are included in the dojo.js file and no dojo.require statement is necessary to ensure that the code is part of the page.

The object passed to dojo.xhrGet and dojo.xhrPost has specific properties that control how the actual XHR object is created and how the response from the server is processed. Some of the properties are required but most are optional. The table below describes each of the possible properties.

The following table describes the properties in the argument passed to either dojo.xhrGet or dojo.xhrPost.

Request Object Properties
Property Description
url String. The location of the server resource being requested.  Corresponds to the url property of the XHR object.
content String. A key/value mapping of properties to be constructed into parameters passed with the request.  For example, query string parameters in GET requests or form fields in POST requests.
timeout Integer. Default: 1000 milliseconds. Number of milliseconds to wait for the server response. When the timeout is exceeded the request should be cancelled and the error callback method should be executed.
form Object. Reference to the DOM element representing the form. Dojo will iterate through the form elements and create name/value pairs to be passed to the server. The dojo.xhrGet function will pass the data in the URL while dojo.xhrPost will include the data in the body of the HTTP request.
preventCache Boolean. Indicates whether the result of the request should be cached and whether requesting a result from the cache is acceptable.
handleAs

String. Default: text

This property determines how Dojo will process the response from the server. When the response is returned, Dojo executes the callback function specified in either the load, error or handle property and passes parameters to the function. The contents of this property determines what object is passed to the callback method.

The following values are possible:

  • text: the data object passed to the callback method will be a string
  • json: the data object passed to the callback method will be an object built from a JSON string returned from the server
  • xml: the data object passed to the callback method will be a DOM object
  • javascript: the data object passed to the callback method will be the responseText property of XHR. The javascript sent from the server will also be executed by Dojo.
load The function that will be called to handle the response from the server when the response is not in error.
error Object. The function that will be called if there is an error in the response.
handle Object. The function that will be called to handle the response from the server for either a successful or unsuccessful response. Specify either handle or both load and error.

Here is the syntax of a simple call to the xhrPost() method:

Syntax
dojo.xhrPost(
 {
  url: url,
  load: callBackFunction,
  content:  {
   param1: value,
   param2: value,
   param3: value
  }
 } );

The code sample below shows how we would change part of our EmployeeAdmin.html document to use Dojo.

Code Sample: AjaxFrameworks/Demos/Dojo/EmployeeAdmin.html

<html>
<head>
<title>Employee Administration</title>
<link rel="stylesheet" type="text/css" href="../Styles/Main.css">
<script type="text/javascript" src="http://o.aolcdn.com/dojo/1.1.0/dojo/dojo.xd.js"></script>
<script type="text/javascript">
 var OutputDiv;
 function GetEmployeeList(URL)
 {
  OutputDiv = document.getElementById("EmployeeList");
  OutputDiv.innerHTML="<h2>Loading...</h2>";

  dojo.xhrPost(
   {
    url: URL,
    handleAs: "text",
    load: Display
   });
 }

 function Display(DATA)
 {
  OutputDiv.style.display="block";
  if (DATA.indexOf("Failed") != -1)
  {
   OutputDiv.className="Warning";
   OutputDiv.innerHTML=DATA;
  }
  else
  {
   OutputDiv.innerHTML = DATA;
  }
 }

 window.onload = function()
 {
  GetEmployeeList("../EmployeeList.jsp");
 }
</script>
</head>
---- Code Omitted ----
Code Explanation

As you can see, we only need to make use of the url, handleAs and method properties of the object that is passed to the xhrPost() method. To pass parameters in with the XMLHttpRequest, we would need to include the content property as well.

Another thing to notice is that the callback function (Display()) no longer needs to check the status and the readyState of the xmlhttp object. This is handled by Dojo. The callback function takes a single parameter, which holds the data passed back from the server. The type of this data depends on the handleAs property.

Exercise: Using Dojo for XMLHttpRequests

Duration: 5 to 15 minutes.

In this exercise, you will complete the transition of the EmployeeAdmin.html file to use Dojo instead of our Ajax.js library.

  1. Open AjaxFrameworks/Exercises/Dojo/EmployeeAdmin.html for editing.
  2. Modify the GetEmployeeForm(), UpdateEmployee(), and EmployeeUpdated() functions to use the Dojo framework.

Prototype (see footnote)

Prototype is a multi-purpose JavaScript toolkit that, according to its website, "aims to ease development of dynamic web applications." Many other libraries, such as script.aculo.us and Rico are built on top of Prototype and the Ruby on Rails framework has built-in support for Prototype. These tie-ins make it likely that Prototype will be around for a long time. Like Dojo, it is client-side specific so it can be used on any platform with any server-side language. Prototype is now well documented at http://www.prototypejs.org/api. However, before there was good documentation on the Prototype site, Sergio Pereira put together some very good online documentation at http://www.sergiopereira.com/articles/prototype.js.html, which is still available.

Downloading Prototype

The latest version of Prototype is freely available for download at http://www.prototypejs.org/download as a .js file. Rename the file to "prototype.js" and save it in a folder on your web server. We have included a copy of it with your class files (/prototype.js).

Using Prototype for Ajax

To make the Prototype library available, include the prototype.js file as you would any other JavaScript library:

<script language="javascript" src="prototype.js"></script>

XMLHttpRequests are made using the Ajax.Request() class, which, when instantiated, takes two parameters: a URL string and an object, which has the following properties and methods:

Ajax.Request() 2nd Parameter Properties
Property Description
method String. Method of request. Usually "get" or "post".
parameters String. Querystring parameters or form fields in POST requests, using the querystring syntax (e.g, "firstname=Nat&lastname=Dunn")
asynchronous Boolean. Defaults to true. Determines whether the request should be made synchronously.
Ajax.Request 2nd Parameter Methods
Property Description
onComplete(xmlhttp) Callback method used when onSuccess or onFailure is not defined or not available. The only parameter is a reference to the XMLHTTP object used to dispatch the request.
onSuccess(xmlhttp) Callback method used when data is successfully returned for this Request. The only parameter is a reference to the XMLHTTP object used to dispatch the request.
onFailure(xmlhttp) Callback method used when data cannot be returned for this Request. The only parameter is a reference to the XMLHTTP object used to dispatch the request.

Here is the syntax of a simple call to the Ajax.Request() constructor:

Syntax
new Ajax.Request(URL, 
 {
  method: "get", //or "post"
  onComplete: CallBackFunction,
  parameters: "param1=value&param2=value&param3=value"
 });

The code sample below shows how we would change part of our EmployeeAdmin.html document to use Prototype.

Code Sample: AjaxFrameworks/Demos/Prototype/EmployeeAdmin.html

<html>
<head>
<title>Employee Administration</title>
<link rel="stylesheet" type="text/css" href="../Styles/Main.css">
<script type="text/javascript" src="../../../prototype.js"></script>
<script type="text/javascript" src="../Scripts/Effects.js"></script>
<script type="text/javascript">
 var OutputDiv;
 function GetEmployeeList(URL)
 {
  OutputDiv = document.getElementById("EmployeeList");
  OutputDiv.innerHTML="<h2>Loading...</h2>";

  new Ajax.Request(URL,
   {
    method: "post",
    onComplete: Display
   });
 }

 function Display(REQ)
 {
  OutputDiv.style.display="block";
  if (REQ.responseText.indexOf("Failed") != -1)
  {
   OutputDiv.className="Warning";
   OutputDiv.innerHTML=REQ.responseText;
  }
  else
  {
   OutputDiv.innerHTML = REQ.responseText;
  }
 }

 window.onload = function()
 {
  GetEmployeeList("../EmployeeList.jsp");
 }
</script>
</head>
---- Code Omitted ----
Code Explanation

As you can see, we only need to make use of the url property and the second parameter's method property and the onComplete method. To pass parameters in with the XMLHttpRequest, we would need to include the parameters property as well.

Like with Dojo, the callback function (Display()) no longer needs to check the status and the readyState of the xmlhttp object as Prototype takes care of this behind the scenes.

Exercise: Using Prototype for XMLHttpRequests

Duration: 5 to 15 minutes.

In this exercise, you will complete the transition of the EmployeeAdmin.html file to use Prototype instead of our Ajax.js library.

  1. Open AjaxFrameworks/Exercises/Prototype/EmployeeAdmin.html for editing.
  2. Modify the GetEmployeeForm(), UpdateEmployee(), and EmployeeUpdated() functions to use the Prototype framework.

Throughout the rest of this manual, we will be using Prototype to handle our XMLHttpRequests.

Other Popular Frameworks

Direct Web Remoting (DWR) (see footnote)

DWR is one of the more popular Java-specific frameworks. It makes it possible to call Java methods directly from JavaScript by blackboxing the data transfer to and from the server to make it feel to the developer as if Java objects were natively available to the browser.

AjaxAnywhere (see footnote)

According to its website, "AjaxAnywhere is designed to turn any set of existing JSP or JSF components into AJAX-aware components without complex JavaScript coding." The major benefit of AjaxAnywhere is that it makes it possible to create Ajax applications without writing much JavaScript. The downside is that it does not provide as much flexibility as the more JavaScript-centric solutions.

Simple Ajax (SAJAX) (see footnote)

Like DWR, Sajax allows you to access server-side code directly from JavaScript. It supports ASP, ColdFusion, Perl, PHP, Python, and Ruby, but not Java.

Sarissa (see footnote)

Sarissa is a JavaScript-centric library that isn't specific to any server-side language. It provides a simple function that emulates Mozilla's XMLHttpRequest for Internet Explorer, but that's about it when it comes to client-server communication. It does make using XSLT in the browser very easy.

Other Frameworks

As noted in the beginning of this lesson, there are many more frameworks. For a good list, see http://ajaxpatterns.org/Ajax_Frameworks.

Ajax Frameworks Conclusion

In this lesson of the Ajax tutorial, you have learned about some common Ajax frameworks and how to use a couple of the most popular to handle XMLHttpRequests.

Footnotes

  1. Available at http://script.aculo.us.

  2. Available at http://openrico.org.

  3. Available at http://ajaxanywhere.sourceforge.net.

  4. Available at http://dojotoolkit.org.

  5. source: http://redesign.dojotoolkit.org/jsdoc/dojo/HEAD/dojo.xhr

  6. Available at http://prototype.conio.net.

  7. Available at http://getahead.ltd.uk/dwr.

  8. Available at http://ajaxanywhere.sourceforge.net.

  9. Available at http://www.modernmethod.com/sajax.

  10. Available at http://sarissa.sourceforge.net/doc.

  11. You may also make use of the Dojo Toolkit hosted on CacheFile.net. This may result in speedier delivery of your pages as browsers may already have the file cached. The URL for version 1.6.0.2 is http://www.cachefile.net/scripts/prototype/1.6.0.2/prototype.js. For the latest version, see http://www.cachefile.net/scripts/prototype.

  12. You may also make use of the Dojo Toolkit hosted on AOL'S Content Delivery Network. This may result in speedier delivery of your pages as browsers may already have the dojo files cached. The URL for version 1.0.2 is http://o.aolcdn.com/dojo/1.0.2/dojo/dojo.xd.js. For the latest version, see http://dev.aol.com/dojo.

To continue to learn Ajax go to the top of this page and click on the next lesson in this Ajax Tutorial's Table of Contents.
Last updated on 2009-03-22

Use of http://www.learn-ajax-tutorial.com (Website) implies agreement to the following:

Copyright Information

All pages and graphics on Website are the property of Webucator, Inc. unless otherwise specified.

None of the content on Website may be redistributed or reproduced in any way, shape, or form without written permission from Webucator, Inc.

No Printing or saving of pages or content on Website

This content may not be printed or saved. It is for online use only.


Linking to Website

You may link to any of the pages on Website; however, you may not include the content in a frame or iframe without written permission from Webucator, Inc.


Warranties

Website is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code and explanations provided on this site are provided without warranties to correctness, performance, fitness, merchantability, and/or any other warranty (whether expressed or implied).


For individual private use only

You agree not to use this online manual to deliver or receive training. If you are delivering or attending a class that is making use of this online manual, you are in violation of our terms of service. Please report any abuse to courseware@webucator.com. If you would like to deliver or receive training using this manual, please fill out the form at http://www.webucator.com/Contact.cfm