| By Anil Sharma | Article Rating: |
|
| April 14, 2007 08:00 AM EDT | Reads: |
2,322 |
This content is reprinted from Real-World AJAX: Secrets of the Masters published by SYS-CON Books. To order the entire book now along with companion DVDs for the special pre-order price, click here for more information. Aimed at everyone from enterprise developers to self-taught scripters, Real-World AJAX: Secrets of the Masters is the perfect book for anyone who wants to start developing AJAX applications.
Source Code Organization - Directory Structure
Let's look at the source code organization in our sample application. It's important from two perspectives: a) it would be useful in browsing the sample code described in the following sections; and b) the directory structure helps visualize the structure of the pages. We use the directory structure below for source code organization.
Root directory
base (framework or base code)
utils (utility JavaScript code)
components (JavaScript code for Components)
css (framework's css file)
app (application code)
js (JavaScript code for the application)
html (Application's HTML files and templates)
css (Application's css files)
images (contains image files used by the application)
MainPage.html (the first page of the application)
In the example code, instead of one MainPage.html, there are many pages called MainPage-1.html, MainPage-2.html, and so on. Each of these corresponds to a step indicated by the number. Each subsequent page is a refinement of the page in the preceding step. We'll use this stepwise refinement approach in the following discussion.
A Sample Application
The rest of this chapter illustrates the concepts discussed above using a sample application. Our sample application is a project management application. It illustrates the use of the navigation bar, tables, forms, and interaction among components. It demonstrates AJAX calls to the back-end servlet. The application has the following pages:
- The main page
- A tabular view for a list of the projects
- A form to edit the selected task
JavaScript Functions as a Class
JavaScript is not an object-oriented language. It doesn't support classes directly. But a JavaScript function can act like a class. The name of the function is like a class name. The variables declared inside the function using "this" keyword are equivalent to the fields of the class. The nested functions act like the methods of a class. A new function can iterate over the properties of an existing function and assign itself. It can then define additional fields and variables. This is equivalent to class inheritance. In the following discussion when we refer to a class it means a JavaScript function that behaves like a class. We use the word class and function interchangeably.
Utility Classes and Functions
To keep it simple, we've refrained from using any existing framework except prototype.js, which, among other things, implements functions for communicating with the server from an AJAX client. We use these functions for sending an AJAX request to the Web server and get its response as a callback. In our sample we use a set of simple utility classes/functions. They are listed in the table below and are discussed later.
ElementCollection
ElementCollection is a utility class. Given an HTML element, it builds an internal list of sub-elements contained within it. It also provides a set of convenience methods and an iterator over the sub-elements.
To instantiate an ElementCollection:
var e = document.getElementById('some-element-id');
var ec = new ElementCollection(e);
The following code is used to iterate over the sub-elements of "e":
var iter = ec.getIterator();
if (iter.hasNext()) {
var subelement = iter.nextElement();
// do something
}
This code is used to get all elements by a given "tag":
var list = ec.getElement('a'); // returns a list of all anchors
var e2 = ec.getFirstElement('a'); // returns the first anchor element
And this code is used to get a lookup table of elements by "id":
var lookupTable = ec.getElementsIndexedById('a');
// returns a lookup table of anchor elements, the key is the "id" of each element.
AjaxEngine for Client/Server Interaction
AjaxEngine is the interface between the client and the server. The client passes a request object to the AjaxEngine. It converts the request to an XML message and sends it to the server using the GET or POST method. The result is communicated back to the client through a callback. Refer to AjaxEngine.js for details of the implementation. You only need to know its "processRequest" method to use it. An example use of this method is shown below. But it's recommended that you understand the request object's details. One important feature of the AjaxEngine is that it implements a queue
of requests. It processes requests in the order they're received. The following section discusses the request and callback functions in a greater detail.
ajaxEngine.processRequest(req); // where 'req' is a request object.
"ajaxEngine" is a global instance of AjaxEngine declared as follows:
var ajaxEngine = new AjaxEngine();
DataRequest Class
The DataRequest class models the AJAX request that's sent to the server. It provides the high-level APIs for building an AJAX message. It is the single place where the client request is converted to an XML message that can be understood by the server. Any change in the message format between the client and server can be reflected here.
The DataRequest is constructed as follows:
var req = new VL.DataRequest(url,
requestCompleted, requestFailed, requestTimedout); // construct request
ajaxEngine.processRequest(req); // send the request to the server
The parameters of the constructor are as follows:
- URL: The target URL as a string.
- requestCompleted: The callback function is invoked if the request succeeds. It's invoked with the response returned by the AJAX call.
- requestFailed: The callback is invoked if the request fails. This is invoked with the error message.
- requestTimedOut: This callback is invoked if the request times out.
Listing 5.5 - Usage of DataRequest and AjaxEngine
function loadTopNaviagation() {
// construct request
var req = new DataRequest(serverURL + 'TopNavBar.html',
requestCompletedNavigationBar,
requestFailedNavigationBar,
requestTimedoutNavigationBar);
// send the request to the server.
ajaxEngine.processRequest(req);
}
// callback if the request succeeds.
function requestCompletedNavigationBar(response) {
// response.responseText gives the result XML in string form
// response.responseXML gives the result XML as DOM
// does something that consumes XML
}
// callback if the request fails.
function requestFailedNavigationBar(dataRequest) {
alert("Request failed, url: " + dataRequest.requestURL);
}
// callback if the request times out
function requestTimedoutNavigationBar(dataRequest) {
alert("Request timedout, url: " + dataRequest.requestURL);
}
Stepwise Refinement of the AJAX Page
In the following section, we'll discuss the implementation of our example application. The approach we'll follow is to refine the application in steps. It starts with the shell main page. In the ensuing steps we'll add a navigation component, navigate to a table view, build a tabular and form view using templates, and so on. The main page is called MainPage-(n) where "n" is a running sequence number starting with 1. MainPage-1.html, MainPage-2.html, etc. corresponds to the steps of the development. The process starts with the main page that is just a shell. In subsequent steps, the main page is refined or sub-pages are added. The following table provides an overview of the steps.
Shell Main Page
Refer to MainPage-1.html inside the root directory of the installation for the following discussion. The main page is a shell with common elements such as a title area, logo, user's name, and logout button. It has two "div" elements that are placeholders for the HTML elements that will be created dynamically.
The HTML that created the placeholder elements is shown below:
Listing 5.6 - Placeholder Elements in HMTL
<div id="NavBarArea" style="width:90%; text-align:left;
padding:0px; margin-top:0px">
Navigation Bar ...
</div>
<div id="MainArea" style="width:90%; text-align:left;
margin-top:0px">
Main area ...
</div>
"NavBarArea" is the placeholder for the navigation bar element. "MainArea" is the placeholder where the contents will be displayed based on user selection. The following sections discuss how the placeholder elements are filled in with actual content.
This content is reprinted from Real-World AJAX: Secrets of the Masters published by SYS-CON Books. To order the entire book now along with companion DVDs, click here to order.
Published April 14, 2007 Reads 2,322
Copyright © 2007 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
About Anil Sharma
Anil Sharma is a founder of Vertex Logic and architect of its AjaxFace product. He is working with Vertex Logic's customers and helping them deploy WEB 2.0 applications built using AjaxFace. These applications are in the areas of online printing, community WEB sites and social networking. He is driving future products of Vertex Logic. Prior to Vertex Logic, he was CTO and founder of Softrock Systems and Component Plus. There he built a model driven application platform using J2EE. His primary interests include user interface infrastructures and model driven applications. He is one of the contributors of the book "Real World AJAX - Secrets of the Master".
- AJAX World RIA Conference & Expo Kicks Off in New York City
- What is Web 3.0?
- AJAXWorld RIA Conference & Expo 2009 West: Call for Papers
- AJAX and RIA 2009: More Choices, Tough Decisions
- Ulitzer’s Amazing First 30 Days in Public Beta
- SYS-CON Announces Government IT Conference & Expo
- RIAs for Web 3.0 Using the Microsoft Platform
- REA Is Where RIA Becomes the Norm
- Why an Application Grid?
- 2nd International Cloud Computing Expo New York Photo Album
- AJAX World RIA Conference & Expo Kicks Off in New York City
- What is Web 3.0?
- Developing Rich Client Applications Using Swing - II
- AJAXWorld RIA Conference & Expo 2009 West: Call for Papers
- AJAX and RIA 2009: More Choices, Tough Decisions
- AJAX World RIA Conference Awards Announced
- WebORB Launched for Flex, Flash, AJAX and Silverlight
- Appcelerator Revolutionizes UI Prototyping
- Adobe Takes LiveCycle into the Cloud
- Ulitzer’s Amazing First 30 Days in Public Beta
- Building a Drag-and-Drop Shopping Cart with AJAX
- What Is AJAX?
- Google Maps! AJAX-Style Web Development Using ASP.NET
- Flashback to January 2006: Exclusive SYS-CON.TV Interviews on "OpenAjax Alliance" Announcement
- AJAXWorld Conference & Expo to Take Place October 2-4, 2006, at the Santa Clara Convention Center, California
- AJAX Sponsor Webcasts Are Now Available at AJAXWorld Website
- How and Why AJAX, Not Java, Became the Favored Technology for Rich Internet Applications
- "Real-World AJAX" One-Day Seminar Arrives in Silicon Valley
- AJAXWorld University Announces AJAX Developer Bootcamp
- AJAX Support In JadeLiquid WebRenderer v3.1







































