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.
Overview of Ajax:
- 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 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.
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.
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.
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.
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.
Ajax implementation can be divided into following steps:
- Getting a request object
- Making a request to a server resource.
- 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:
The request object obtained is responsible for communicating with the server. The XMLHttpRequest object has following methods and 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
- open(): Sets up a new request to a server.
- send(content): Sends a request to a server.
- abort(): Bails out of the current request.
- setRequestHeader("<name>", "<value>")
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.
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
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.
Handling and processing the server response data:
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.
But the above given callback function is a short-sighted and error-prone approach to Ajax programming.
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
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:
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.
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
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.
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.
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.
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.
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.
- getElementsByTagName(elementName) returns a list of element nodes with the supplied name.
- getElementById(id) returns an element node with the supplied id.
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:
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.
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:
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.
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.
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:
- 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.
- 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.
- 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.
- 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.
- 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.
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:
- 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.
- 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.
- 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).
- 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.
- 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.
- 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.
- 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.
- 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.
- SOPHISTICATED USER INTERFACE CONTROLS: Controls such as tree controls, menus, and progress bars may be provided that do not require page refreshes.
- 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.
- 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.
- 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.
The execution speed can always be improved by optimizing the codes. The process of measuring the execution speed is called profiling.
This is illustrated below.
Optimization – AJAX
Consider the following example:
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.
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.
Avoid writing output multiple times to the document, concatenate the data and then write all in one go.
The above function can be optimized as follows to increase the execution speed.
Consider the example below:
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.
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.
- w3schools AJAX tutorial - (http://www.w3schools.com/ajax/default.asp)
- Mastering AJAX Series on IBM DeveloperWorks - (http://www.ibm.com/developerworks/web/library/wa-ajaxintro1.html)
- w3schools XML DOM Tutorial - (http://www.w3schools.com/dom/default.asp)
- w3schools HTML DOM Tutorial - (http://www.w3schools.com/htmldom/default.asp)
- AJAX Tutorial - (http://www.ajaxtutorial.net/)