RSS

Ajax and DOM

24 Nov

Abstract

Ajax is a powerful approach to building Web sites and it’s not nearly as hard to learn as an entire new language.

Before I dig into what Ajax is, though, let’s spend just a few moments understanding what Ajax does. Today’s applications can be divided into two broad categories:

  • Desktop applications
  • Web applications

Desktop applications are installed completely on the computer. The code that runs these applications resides on the desktop. Web applications on the other hand run on a Web server we access the application with the Web browser. More important than where the code for these applications runs, though, is how the applications behave and how we interact with them. Desktop applications are usually pretty fast (they’re running on your computer), have great user interfaces (usually interacting with your operating system), and are incredibly dynamic. On the other hand, Web applications provide services we could never get on our desktop . However, with the power of the Web comes the time lag — waiting for a server to respond, waiting for a screen to refresh, waiting for a request to come back and generate a new page. This is where the Ajax steps in to make the interaction faster. 

Ajax attempts to bridge the gap between the functionality and interactivity of a desktop application and the always-updated Web application. We can have dynamic user interfaces and fancier controls like a desktop application, but it’s available to on a Web application. Most Web applications use a request/response model that gets an entire HTML page from the server. The result is a back-and-forth operation that usually involves clicking a button, waiting for the server, clicking another button, and then waiting for some more time. With Ajax, we can use a request/response model that never leaves users waiting for a server to respond.

AJAX Overview

Overview of Ajax:

  • AJAX stands for Asynchronous JavaScript And XML.
  • AJAX is a type of programming made popular in 2005 by Google (with Google Suggest).
  • AJAX is not a new programming language, but a new way to use existing standards.
  • With AJAX we can create better, faster, and more user-friendly web applications.
  • AJAX is based on JavaScript and HTTP requests.
  • With AJAX, the JavaScript can communicate directly with the server, using the
  • JavaScript XMLHttpRequest object. With this object, the JavaScript can trade data with a web server, without reloading the page.
  • AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages.
  • AJAX is a browser technology independent of web server software.

Here are the basic technologies involved in Ajax applications:

  • HTML
  • JavaScript code is the core code running Ajax applications and it helps facilitate communication with server applications.
  • XML
  • DOM, the Document Object Model, will be used (through JavaScript code) to work with both the structure of your HTML and (in some cases) XML returned from the server.

Classic Vs AJAX Web Application

In any web application that we develop will have HTML pages rendered in the client and on submit of the (aspx / jsp / jsf) page, the screen is refreshed and a new HTML page will be rendered. 

AJAX Web Application will also render only HTML pages and on submit the page will get refreshed. But, if we need any other information from the web server before the user submits the page or if we need to show any data as the user start using the web page, we can’t do so at present. It’s possible by implementing AJAX using a JavaScript method in the HTML page which in-turn gets fired based on certain client side events. This JavaScript method will call a Web Service or a Server side method to get the data and can be shown using DHTML / CSS in the client or show an alert or validate certain data and inform the user before he submits the page. Simply put, classic model is synchronous, AJAX model is asynchronous. What makes AJAX based clients unique is that the client contains page-specific control logic embedded as JavaScript technology. The page interacts with the JavaScript technology based on events such as the document being loaded, a mouse click, focus changes, or even a timer. AJAX interactions allow for a clear separation of presentation logic from the data. An HTML page can pull in bite-size pieces of data as needed rather than reloading the whole page every time a change needs to be displayed. AJAX will require different server-side architecture to support this interaction model. Traditionally, server-side web applications have focused on generating HTML documents for every client event resulting in a call to the server. The clients would then refresh and  re-render the complete HTML page for each response. Rich web applications focus on a client fetching an HTML document that acts as a template or container into which to inject content, based on client events using XML data retrieved from a server-side component. While seemingly simplistic, AJAX opens doors for Web-application developers that had previously been shut. It relies on nothing but the built-in browser internals. No extra software needs to be distributed to users, making AJAX an attractive option for companies that are concerned about the security and logistical implications of distributing installed software to users.

The traditional Web-application architecture (sometimes referred to as the postback model) is inefficient because it wastes communications bandwidth. Every hyperlink activation or buttonpress results in a postback (or reload) of an entire Web page, when perhaps all that was required was a tiny block of text from the database. AJAX solves this problem with XMLHttpRequest.

ajaxdom1

Using XML HTTP and JavaScript, a developer can make an asynchronous request for a block of information from a server without needing to reload an entire page. The result is Web applications that react more quickly to user interaction.

For example, a user might want to see the details about a customer in a Web page. In a traditional Web application, the user might have to click and wait for the entire page to refresh before seeing those details. In an AJAX model, the user could click on the customer’s name and have the data retrieved instantly from the server, then displayed directly on the Web page.

All major browser platforms now support AJAX, including Internet Explorer, Mozilla FireFox, Netscape, Opera and Safari. There’s also a move toward standardization of XML HTTP, the core component of AJAX. Performing targeted information updates, or microupdates, can substantially reduce network loads, in addition to faster interaction with live data. Benefits can be measured through total bytes transferred, total download time and steps/seconds to complete a task.

Lifecycle of an Ajax Application

The Ajax lifecycle is more like that of a traditional GUI than a traditional web application, with DOM objects acting like GUI widgets. The script registers event listeners on DOM objects, and manipulates the DOM in response to those events. As part of the event-processing cycle, the server may be invoked. There’s actually a slight complication here in that the server calls are asynchronous, so the event-listening phase is split from the event responding phase.

Here’s a typical Ajax lifecycle within the browser:

  • Visit: The user visits a site the usual way, i.e. by clicking on a link or typing a URL.
  • Initialization The page initially loads. Callbacks are established to handle user input
  • Event Loop:
    • Browser Event An event occurs, such as a key press.
    • Server Request The browser sends a request to the server.
    • …<Server processes the event>
    • Server Response A moment later, the server responds, and the response is passed into a request callback function, one that was specified when the request was issued.
    • Browser Update The request callback function updates the DOM, including any JavaScript variables, according to the response.

In particular, many events are handled locally and don’t actually trigger a trip to the server. Also, some Ajax applications are short-lived and the browser interaction is eventually terminated with the user submitting a form. Others remain to interact with the user as long as they are in the user’s browser.

Note that the Browser Event and the Server Request occur in one thread, and the Server Response and Browser Update occur in a separate thread. This is due to the asynchronous nature of the server request.

Implementing AJAX

The heart of the AJAX is the XMLHttpRequest Object. It is a JavaScript object and handles all server communication. In a normal Web application, users fill out form fields and click a Submit button. Then, the entire form is sent to the server, the server passes on processing to a script and when the script is done, it sends back a completely new page. That page might be HTML with a new form with some data filled in or it might be a confirmation or perhaps a page with certain options selected based on data entered in the original form. Of course, while the script or program on the server is processing and returning a new form, users have to wait. Their screen will go blank and then be redrawn as data comes back from the server. This is where low interactivity comes into play — users don’t get instant feedback and they certainly don’t feel like they’re working on a desktop application.

Ajax essentially puts JavaScript technology and the XMLHttpRequest object between your Web form and the server. When users fill out forms, that data is sent to some JavaScript code and not directly to the server. Instead, the JavaScript code grabs the form data and sends a request to the server. While this is happening, the form on the users screen doesn’t flash, blink, disappear, or stall. In other words, the JavaScript code sends the request behind the scenes; the user doesn’t even realize that the request is being made. Even better, the request is sent asynchronously, which means that JavaScript code (and the user) doesn’t wait around on the server to respond. So users can continue entering data, scrolling around, and using the application. 

Then, the server sends data back to JavaScript code (still standing in for the Web form) which decides what to do with that data. It can update form fields on the fly, giving that immediate feeling to your application — users are getting new data without their form being submitted or refreshed. The JavaScript code could even get the data, perform some calculations, and send another request, all without user intervention! This is the power of XMLHttpRequest. It can talk back and forth with a server all it wants, without the user ever knowing about what’s really going on. The result is a dynamic, responsive, highly-interactive experience like a desktop application, but with all the power of the Internet behind it.

Ajax implementation can be divided into following steps:

  1. Getting a request object
  2. Making a request to a server resource.
  3. Handling and processing the server response data

Getting a request object

The request object is implemented in IE as Microsoft.XMLHTTP object or Msxml2.XMLHTTP object whereas other browsers(Mozilla, Firefox, Safari, Opera, and almost every other non-Microsoft browser that supports Ajax in any form or fashion.) implement it as XMLHttpRequest object. 

A cross browser Ajax implementation can create request object in the below given manner:

var xmlHttp;try{          xmlHttp = new ActiveXObject(“Msxml2.XMLHTTP”);} catch (e) {

try {

xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);

} catch (e1) {

try {

xmlHttp = new XMLHttpRequest();

} catch (e2) {

xmlHttp = false;

alert(“Error initializing XMLHttpRequest!”);

}

}

}

The request object obtained is responsible for communicating with the server. The XMLHttpRequest object has following methods and properties:

Properties:

  • Onreadystatechange: Event handler for an event that fires at every state change
  • readyState: Provides the current HTML ready state.
  • responseText: The text that the server sends back to respond to a request.
  • responseXML: DOM-compatible document object of data returned
  • status: HTTP status code
  • statusText: String message associated with the status code

Methods:

  • open(): Sets up a new request to a server.
  • send(content): Sends a request to a server.
  • abort(): Bails out of the current request.
  • getAllResponseHeaders()
  • getResponseHeader(“<headerName>”)
  • setRequestHeader(“<name>”, “<value>”)

Making a request to a server resource:

We can begin the request/response cycle once we have the request object. XMLHttpRequest’s only allows us to make requests and receive responses. Everything else like changing the user interface, swapping out images, even interpreting the data that the server sends back — is the job of JavaScript, CSS, or other code in the pages. Ajax implements sandbox security model and as a result, our Ajax code (and specifically, the XMLHttpRequest object) can only make requests to the same domain on which it’s running.

We use the open() of the XMLHttpRequest object to create a request to the server. The open method takes in the following parameters:

  • request-type: The type of request to send. Typical values are GET or POST, but you can also send HEAD requests.
  • url: The URL of the server resource to connect to.
  • asynch: True if you want the request to be asynchronous and false if it should be a synchronous request. This parameter is optional and defaults to true.
  • username: If authentication is required, you can specify the username here. This is an optional parameter and has no default value.
  • password: If authentication is required, you can specify the password here. This is an optional parameter and has no default value.
xmlHttp.open(“GET”, url, true);

The send() method of the request object is used to send the request to the server. The send method takes in the data object, required to be send to the server, as the parameter. While using the GET method we normally send the data in the URL. When there is no need to pass data along through send(), then just pass null as the argument to this method

xmlHttp.setRequestHeader(“Content-Type”, “text/plain”);xmlHttp.open(“GET”, url, true);   xmlHttp.onreadystatechange = callback function;

request.send(null);

While sending a POST request, as opposed to a GET request, it requires a plaintext or xml to be sent with the request. However, sending an XML across to the server makes the process slow. The XML sent should also comply with the XML format accepted by the server.

xmlHttp.setRequestHeader(“Content-Type”, “text/xml”);xmlHttp.open(“POST”, url, true);   xmlHttp.onreadystatechange = callback function;

request.send(parameterString/parameterXMLString);

Handling and processing the server response data:

In the previous section we understood how to obtain a XMLHttpRequest object and making a server request. After sending the request the response data obtained from the server is processed in the JavaScript code of your page.

The onreadystatechange property of the request object is used to lookup the JavaScript function responsible for handling the server response. These methods are popularly known as callback methods. A callback allows the server to call back into your Web page’s code. It gives a degree of control to the server, as well; when the server finishes a request, it looks in the XMLHttpRequest object and specifically at the onreadystatechange property. Whatever method is specified by that property is then invoked. It’s a callback because the server initiates calling back into the Web page — regardless of what is going in the Web page itself.

In fact, the callback method is called every time the HTTP ready state changes. So what does that mean? An HTTP ready state indicates the state or status of a request. It’s used to figure out if a
request has been started, if it’s being answered, or if the request/response model has completed. It’s also helpful in determining whether it’s safe to read whatever response text or data that a server might have supplied. There are five ready states in any Ajax applications:

  • 0: The request is uninitialized (before we called open()).
  • 1: The request is set up, but hasn’t been sent (before we called send()).
  • 2: The request was sent and is being processed (we usually get content headers from the response at this point).
  • 3: The request is being processed; often some partial data is available from the response, but the server hasn’t finished with its response.
  • 4: The response is complete; we get the server’s response and use it.

Below given is the example of a call back function skeleton:

function updatePage() {
if (request.readyState == 4) {
//do something
}
}

But the above given callback function is a short-sighted and error-prone approach to Ajax programming.

Suppose a script requires authentication and the request does not provide valid credentials, the server will return an error code like 403 or 401. However, the ready state will be set to 4 since the server answered the request (even if the answer wasn’t what was expected for the request). As a result, the user is not going to get valid data and might even get a nasty error when the JavaScript tries to use non-existent server data. This problem is solved by using the status property of the XMLHttpRequest object. It takes minimal effort to ensure that the server not only finished with a request, but returned an “Everything is OK” status code (200) reported through the status property of the XMLHttpRequest object. The following function checks the status of the request:

function updatePage() {
if (request.readyState == 4) {
if (request.status == 200) {
//do something
} else
alert(“status is ” + request.status);
}
}

With the addition of a few lines of code, we can be certain that if something does go wrong, the user will get a (questionably) helpful error message rather than seeing a page of garbled data with no explanation.
With ready states and the server’s response in our bag of Ajax programming techniques, we’re ready to add another level of sophistication to our Ajax applications — working with HTTP status codes.

  • 401: Unauthorized
  • 403: Forbidden
  • 404: Not Found

We can add another layer of control and responsiveness (and particularly more robust errorhandling) to our Ajax applications, by checking the status codes in a request and respond appropriately and handling them.

function updatePage() {
if (request.status == 200) {
//do something
} else if (request.status == 404) {
alert (“Requested URL is not found.”);
} else if (request.status == 403) {
alert(“Access denied.”);
} else
alert(“status is ” + request.status);
}
}

The response from the server can be obtained in either the xml format or the plain text format. Response is handled in the JavaScript as shown below:

function updatePage() {
if (request.readyState == 4) {
if (request.status == 200) {
var response = request.responseText; /// for the output in text format.
OR
var xmlDoc = request.responseXML; /// for output in XML format.
// response has the XML response from the server
alert(response);
}
}
}

The HTML Document can then be updated or modified based on the response received.
The HTML page is treated as a HTML DOM. The browser represents the HTML Document as a set of objects, each of which can be changed, added to, or deleted.

DOM – Document Object Model

The Document Object Model is a W3C standard .Because of that, all modern Web browsers support the DOM. The DOM is also a cross-language specification; in other words, you can use it from most of the popular programming languages

The HTML web pages are all about the organization of the content on the page. Markup is all about providing this level of organization; a p indicates that text is in a paragraph, img denotes an image, div divides a page up into sections, and so forth. The browser takes all this textual organization and turns it into something much more interesting — a set of objects, each of which can be changed, added to, or deleted. Today’s web browsers change the markup language pages into an object tree structure.

For example the below given HTML page is converted to the shown tree structure:

<html>
<head>
<title>Trickier nesting, still</title>
</head>
<body>
<div id=”main-body”>
<div id=”contents”>
<table>
<tr><th>Steps</th><th>Process</th></tr>
<tr><td>1</td><td>Figure out the <em>root
element</em>.</td></tr>
<tr><td>2</td><td>Deal with the <span id=”code”>head</span>
first,
as it’s usually easy.</td></tr>
<tr><td>3</td><td>Work through the <span id=”code”>body</span>.
Just <em>take your time</em>.</td></tr>
</table>
</div>
<div id=”closing”>
This link is <em>not</em> active, but if it were, the answers
to this <a href=”answers.html”><img src=”exercise.gif” /></a>
would be there. But <em>do the exercise anyway!</em>
</div>
</div>
</body>
</html>
domimage

The above given tree structure is the DOM tree notation of the HTML page. DOM stands for Document Object Model and is a specification available from the World Wide Web Consortium. More importantly though, the DOM defines the objects’ types and properties that allow a browser to represent markup.

Node:

A node is the most basic object type in the DOM. In fact, almost every other object defined by the DOM extends the node object. In a DOM tree, almost everything is a node. Every element is at its most basic level a node in the DOM tree. Every attribute is a node. Every piece of text is a node.

According to the DOM, everything in an HTML document is a node.The DOM says that:

  • The entire document is a document node
  • Every HTML tag is an element node
  • The texts contained in the HTML elements are text nodes
  • Every HTML attribute is an attribute node
  • Comments are comment nodes

Properties of a node

The key properties of a DOM node are:

  • nodeName reports the name of the.
  • nodeValue gives the “value” of the node.
  • nodeType gives the type of node(element node, attribute node, text node or document node)
  • parentNode returns the node’s parent.
  • childNodes is a list of a node’s children.
  • firstChild is just a shortcut to the first node in the childNodes list.
  • lastChild is another shortcut, this time to the last node in the childNodes list.
  • previousSibling returns the node before the current node. In other words, it returns the node that precedes the current one, in this node’s parent’s childNodes list .
  • nextSibling is similar to the previousSibling property; it turns the next node in the parent’s childNodes list.
  • attributes is only useful on an element node; it returns a list of an element’s attributes.

Methods of a node

Next up are the methods available to all nodes:

  • insertBefore(newChild, referenceNode) inserts the newChild node before the referenceNode.
  • replaceChild(newChild, oldChild) replaces the oldChild node with the newChild node.
  • removeChild(oldChild) removes the oldChild node from the node the function is run on.
  • appendChild(newChild) adds the newChild node to the node this function is run on.
  • newChild is added at the end of the target node’s children.
  • hasChildNodes() returns true if the node it’s called on has children, and false if it doesn’t.
  • hasAttributes() returns true if the node it’s called on has attributes, and false if there are no attributes.

Common node types

In most Web applications, you’ll only work with four types of nodes:

  • Document node represents an entire HTML document.
  • Element nodes represent HTML elements like a or img.
  • Attribute nodes represent the attributes on HTML elements, like href (on the a element) or src (on the img element).
  • Text nodes represent text in the HTML document, like “Click on the link below for a complete set list.” This is the text that appears inside elements like p, a, or h2.

Document node

The first node type is used in almost every piece of DOM-based code: the document node. The document node is actually not an element in an HTML (or XML) page, but the page itself. So in an HTML Web page, the document node is the entire DOM tree. In JavaScript, the document node can be accessed by using the document keyword:

// These first two lines get the DOM tree for the current Web page, and then the <html> element
for that //DOM tree
var myDocument = document;
var htmlElement = myDocument.documentElement;

The document keyword in JavaScript returns the DOM tree for the current Web page. From there, we can navigate to and work with all the nodes in the tree.

We can also use the document object to create new nodes, using methods like these:

  • createElement(elementName) creates an element with the supplied name.
  • createTextNode(text) creates a new text node with the supplied text.
  • createAttribute(attributeName) creates a new attribute with the supplied name.

The key thing to note is that these methods create nodes, but do not attach them or insert them into any particular document. For this, we have to use one of the insertBefore() or appendChild().

var pElement = myDocument.createElement(“p”);
var text = myDocument.createTextNode(“Here’s some text in a p element.”);
pElement.appendChild(text);
bodyElement.appendChild(pElement);

Element node

In an HTML DOM, every HTML tag is an element node

  • Methods that relate to working with attributes:
  • getAttribute(name) returns the value of the attribute named name.
  • removeAttribute(name) removes the attribute named name.
  • setAttribute(name, value) creates an attribute named name, and sets its value to value.
  • getAttributeNode(name) returns the attribute node named name.
  • removeAttributeNode(node) removes the attribute node that matches the supplied node.

Methods that relate to finding nested elements:

  • getElementsByTagName(elementName) returns a list of element nodes with the supplied name.
  • getElementById(id) returns an element node with the supplied id.
var imgElement = document.createElement(“img”);
imgElement.setAttribute(“src”,
imgElement.setAttribute(“width”, “130”);
imgElement.setAttribute(“height”, “150”);
bodyElement.appendChild(imgElement);

In the code above, the JavaScript creates a new img element, sets up some attributes, and then adds it to the body of the HTML page.

Attribute node

The DOM represents attributes as of the HTML tags, and we can always get an element’s attributes using the attributes property of an element, as shown here:

// Remove all the top-level <img> elements in the body
var imgElements = bodyElement.getElementsByTagName(“img”);
for (i=0; i<imgElements.length; i++) {
var imgElement = imgElements.item[i];
// Print out some information about this element
var msg = “Found an img element!”;
var atts = imgElement.attributes;
for (j=0; j<atts.length; j++) {
var att = atts.item(j);
msg = msg + “\n ” + att.nodeName + “: ‘” + att.nodeValue + “‘”;
}
alert(msg);
bodyElement.removeChild(imgElement);
}

We use the methods available on the element node to work with attributes. The methods are as follows:

  • getAttribute(name) returns the value of the attribute named name.
  • removeAttribute(name) removes the attribute named name.
  • setAttribute(name, value) creates an attribute named name and sets its value to value.

Text node

The last type of node in working with HTML DOM trees is the text node. We use the nodeValue property to get the text from a text node, as shown here:

var pElements = bodyElement.getElementsByTagName(“p”);
for (i=0; i<pElements.length; i++) {
var pElement = pElements.item(i);
var text = pElement.firstChild.nodeValue;
alert(text);
}

A few other methods are specific to text nodes. These deal with adding to or splitting the data in a node:

  • appendData(text) adds the text you supply to the end of the text node’s existing text.
  • insertData(position, text) allows you to insert data in the middle of the text node. It inserts the text you supply at the position indicated.
  • replaceData(position, length, text) removes the characters starting from the position indicated, of the length indicated, and puts the text you supply to the method in the place of the removed text.

What type of node?

Most of what we have seen so far assumes we already know what type of node we are working with, which isn’t always the case. So we need to figure out what type of node we have before we can do much with it.

The DOM node type defines several constants, like this:

  • Node.ELEMENT_NODE is the constant for the element node type.
  • Node.ATTRIBUTE_NODE is the constant for the attribute node type.
  • Node.TEXT_NODE is the constant for the text node type.
  • Node.DOCUMENT_NODE is the constant for the document node type.

We use the nodeType property to compare a node to the above constants, as shown here:

var someNode = document.documentElement.firstChild;
if (someNode.nodeType == Node.ELEMENT_NODE) {
alert(“We’ve found an element node named ” + someNode.nodeName);
} else if (someNode.nodeType == Node.TEXT_NODE) {
alert(“It’s a text node; the text is ” + someNode.nodeValue);
} else if (someNode.nodeType == Node.ATTRIBUTE_NODE) {
alert(“It’s an attribute named ” + someNode.nodeName
+ ” with a value of ‘” + someNode.nodeValue + “‘”);
}

WHY USE AJAX?

Building a web application that employs AJAX is more difficult than building it the classic way. We need to go to extra lengths to make sure that the user experience is and remains enjoyable, and not annoying. With all the hype going around AJAX, a lot of applications that do not have a real need for it have been built. These are toys meant to prove that AJAX is fun, but with little or no use in real-life situations. The decision whether an application would benefit from using AJAX or not is entirely up to the developer.

Advantages of AJAX

Here are some of the advantages AJAX has over classic web development techniques:

  1. The interface is much more responsive, as explained before, because only a small part of the page is transferred at a time. The user has the feeling that changes are instantaneous.
  2. In a classic web application, when the web server sends a web page to the browser, it can use multiple connection threads to speed up delivery. However, this happens for content only – what is between the <body> tags. All script and CSS files linked in the page’s <head> section are transferred using only one connection thread, which diminishes performance. With AJAX, we only have to load the basic scripts and CSS files, and request the rest as content, through multiple connections.
  3. Waiting time is reduced – when the visitor submits a form, they no longer have to wait for the entire page to be rebuilt and re-transmitted by the server. Instead, only the relevant content changes, and in non-critical cases, the visitor can still work while the data is being submitted.
  4. If a page section encounters an error, other sections are not affected (if not logically linked) and the data already entered by the user is not lost. This way, the application fails graciously, without causing head-aches for the users.
  5. Traffic to and from the server is reduced considerably – because we do not have to send the entire page content (CSS, images, static sections), the bandwidth usage is most likely to decrease.

Disadvantages of AJAX

As with most new web development techniques, AJAX has its critics. There are a couple of disadvantages that need to be considered before considering an AJAX-based solution:

  1. Building an AJAX-powered application can increase development time and costs. It is usually considered more difficult than building a classic web application, because of the mixture of technologies and the special concern about everything going smoothly. However, because it is dealing with relatively known technologies, AJAX is easy to learn.
  2. Although AJAX relies on existing and mature technologies like Javascript, HTML and CSS, the available frameworks and components still need to completely mature. Tools like the Dojo toolkit or the Rico framework are just a milestone on this long road. More frameworks that target a specific area are likely to come your way. 
  3. Not all concerns regarding security and user privacy have been answered. This fueled a wave of criticism about how safe is the AJAX way of building applications. 
  4. Using AJAX to asynchronously load bits of content into an existing page conflicts with the way we are used to navigate and create bookmarks in modern browsers. Because viewing some part of the page information no longer corresponds to a newly loaded page, the browser history and bookmarks will not be able to restore the exact page state. Also, clicking the Back button in a browser might not have any effect, since the URL was unchanged (even if parts of the page were changed).
  5. AJAX is not meant to be used in every application. A much better idea than creating complete AJAX applications would be to scatter AJAX features within the application.
  6. The biggest concern with AJAX is accessibility. This is because not all browsers (especially older ones) have complete support for JavaScript or the XMLHttpRequest object. Some of the visitors do have browsers with the required features, but they choose or have to turn off JavaScript support. When you design the application you must make sure that a fail-safe solution exists for those users, so it can be accessed by anyone. Further more, the way to access and use the XMLHttpRequest object in Internet Explorer and other browsers is different, which leads to a fork in the code and the need to treat each case separately.
  7. The last disadvantage lies in the actual XMLHttpRequest object itself. Due to security constraints, you can only use it to access information from the host that served the initial page. If you need to display information from another server, it is not possible within the AJAX paradigm.

Some uses of AJAX in a J2EE Application:

  1. REALTIME FORM DATA VALIDATION: Form data such as user ids, serial numbers, postal codes, or even special coupon codes that require server-side validation can be validated in a form before the user submits a form.
  2. AUTO-COMPLETION: A specific portion of form data such as an email address, name, or city name may be auto-completed as the user types. Another use can be automatic filling of data based on some entry or selection in the form.
  3. MASTER DETAILS OPERATIONS: Based on a client event an HTML page can fetch more detailed information on data such as a product listing that enables the client to view the individual product information without refreshing the page.
  4. SOPHISTICATED USER INTERFACE CONTROLS: Controls such as tree controls, menus, and progress bars may be provided that do not require page refreshes.
  5. REFRESHING DATA ON THE PAGE: HTML pages may poll data from a server for up to date data such as scores, stock quotes, weather, or application specfic data.
  6. SERVER-SIDE NOTIFICATIONS: An HTML page may simulate a server-side push by polling the server for event notifications which may notify the client with a message, refresh page data, or redirect the client to another page.
  7. INFORMATION POP-UPS: We can display information about some of the required fields in the page in the form of pop-ups attached to onmouseover event. 

Performance Considerations

An application is really useful only when it functions at a reasonable speed. The performance depends on two factors – how fast a program runs and the amount of resources it consumes. This is critical for AJAX development as the AJAX based applications involve lots of JavaScript codes and DOM elements. JavaScript is relatively a slow language and does not do calculations as fast as any other programming languages. Therefore we should try to do the as much of calculation as possible in the server. Also DOM elements occupy considerable amount of memory. As execution speed and memory consumption are two important factors affecting the performance of an application, excessive care has to be taken while developing AJAX based applications.

Execution Speed

The execution speed can always be improved by optimizing the codes. The process of measuring the execution speed is called profiling. 

To measure the execution time in JavaScript codes, instantiate Date Objects in the beginning and ending of execution parts. Subtracting these two will give the time taken for that execution in milliseconds. This is a simple way to find out the execution time for a JavaScript programming unit.

This is illustrated below.

function executionTime(){
var begin = new Date();
// execution part – programming unit with complex logics
var end = new Date();
var timeTaken = begin – end; // This variable gives the execution
//time for the execution unit
}

Optimization – AJAX

Some optimization techniques for AJAX (JavaScript codes and DOM elements) are mentioned in the subsequent sections.

Dot notations

In JavaScript the variables of objects in the deeply nested hierarchy can be specified using dots as follows:

var hour= object1.clock.hands.hour;
var minute= object.1clock.hands.minute;
var second= object1.clock.hands.second;

The variables available in the hands object i.e. hour, minute, second are retrieved by doing nine look ups. The hands object is looked up for each and every variable’s retrieval which could have been avoided by compiler optimization as Java does. But JavaScript does not do this optimization. Therefore the programmer has to do the optimization in such scenarios in the code itself. The above code can be optimized to make five look ups only as follows.

var element = object1.clock.hands;
var hour= element.hour;
var minute= element.minute;
var second= element.second;

Optmizing Loops:

Consider the following example:

function loopCounter(var count){
var value=0;
for(var i=0;i<count;i++){
value++;
}
return value;
}
function realLogic(var count){
for(var i=0;i<loopCounter(count);i++){
// do some complex logic
}
}

In the above mentioned examples, the realLogic(count) function will take a long time as the function loopCounter(count) used in the condition part of For loop will have to executer for all the loop iterations. This function can be optimized as follows so that the loopCounter(count) function will be called only once and the rest of the logic will remain intact.

function realLogic(var count){
var condition =loopCounter(count);
for(var i=0;i<condition;i++){
// do some complex logic
}
}

Thus this simple optimization of removing the function call from the condition part of for loop to before for loop will increase the execution time of the programming part considerably.

DOM Manipulation

Avoid writing output multiple times to the document, concatenate the data and then write all in one go.

function modifyData(){
var element = document.getElementById(‘dest’);
element.innerHTML = ‘’; // Clear out the previous
element.innerHTML += modifyTitle();
element.innerHTML += modifyData();
element.innerHTML += modifyFooter();
}

The above function can be optimized as follows to increase the execution speed.

function modifyData ()
{
var elementText = modifyTitle () + modifyData () + modifyFooter();
document.getElementById(‘dest’).innerHTML = elementText;
}

Consider the example below:

var newElement = document.createElement(“div”);
var appendElement = document.getElementById(“append”);
appendElement.appendChild(newElement);
for(var i=0;i<count;i++){
// Add few more elements to the newElement
var element1== document.createElement(“div”);
//Apply style/logic to element1
newElement.append(element1);
}

Optimized code:

var newElement = document.createElement(“div”);
var appendElement = document.getElementById(“append”);
for(var i=0;i<count;i++){
// Add few more elements to the newElement
var element1== document.createElement(“div”);
//Apply style/logic to element1
newElement.append(element1);
}
appendElement.appendChild(newElement);

Conclusion

We have seen that AJAX interactions can solve many problems. J2EE technology provides a good base to develop and deploy AJAX-based applications with APIs for tying in HTTP processing, databases, web services, XML processing, and business objects. With a better understanding of this interaction model, today’s applications can become more interactive, providing the end user with a better experience.

What is particularly attractive about this is that AJAX applications do not require a separate plug-in, and are platform and browser-neutral. That said, AJAX is not supported as well in older browsers. Care needs to be taken in writing client-side script that accounts for the differences between browsers. Using AJAX requires that we use the latest browser versions that support the XMLHttpRequest object needed for AJAX interactions. Using AJAX also requires a great deal of client-side JavaScript technology and CSS. As an application architect or developer, you will need to weigh the needs of having a rich application against browser support, architecture complexity, and developer training. As the AJAX programming model evolves, existing technologies and frameworks will make this transition easier.

Despite some drawbacks, AJAX has generated real excitement with its promise of more responsive Web interactions. Hopefully by now you realize that AJAX is simply exchanging information over HTTP in the background of a page, and updating that page dynamically based on the results.

References

Advertisements
 
3 Comments

Posted by on November 24, 2008 in Web

 

Tags: , , , ,

3 responses to “Ajax and DOM

  1. andrian

    November 24, 2009 at 5:18 pm

    error”>alert(document.cookie);

     
  2. anon_anon

    November 27, 2009 at 7:04 pm

    You may want to look at vtd-xml as the state of the art in XML processing, consuming far less memory than DOM

    vtd-xml

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: