Software development companies have chosen more and more often for the development of web applications. However, it is important to keep in mind that the development of web applications changes a set of concepts with which we’re used to dealing with in software development. The recklessness towards these differences can lead to the development of web applications that sub-optimize, among other things, data transfer which will give the user a notion of little effectiveness and slowness. An example of this notion is when a user waits the loading of an entire page and sees only little changes, such as the update of a selection box or that of a field with database dynamically acquired values. AJAX surfaces in this context, making possible the exchange of only the necessary information between browser and the applications server.
In this article, we will present a simple web application that uses AJAX to communicate in a more efficient manner with the applications’ server and to update its content based on database contained information.
Introduction to AJAX
What is AJAX?
· XHTML/CSS: used for interface presentation with the user. XHTML is nothing but an XML based HTML 4 re-management. Therefore, XHTML documents can be manipulated and validated with standard XML tools. CSS, on the other hand, is a mechanism that can be used to add style (sources, colors, spaces, etc) to XHTML documents.
· DOM: is a model of objects for XML document access and modifications. It is a standard way for applications and scripts to work with XML documents.
· XML/XSLT: represent a document format and a language that allows these documents’ transformation. A XSLT document, for example, can be used to transform a data filled XML document into a XHTML document.
How to use AJAX in a web application?
The Perfect Plan
Detectives Keith Frazier (Denzel Washington) and Bill Mitchell (Chiwetel Ejiofor) are called to Manhattan Trust bank, in Wall Street, where 50 people are held hostage by four robbers led by Danton Russell (Clive Owen).
V for Vendetta
Mission Impossible III
Table 1. Application Example.
Listing 1. searchForSynopsis(idMovie) Function Code
function searchForSynopsis (idMovie)
if (window.ActiveXObject) // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) // não IE
req = new XMLHttpRequest();
var synopsis = document.getElementById("synopsis");
synopsis.innerHTML = req.responseText;
req.open("GET", "movie" + idMovie + ".html", true);
As we can see, in this code an object called `req', XMLHttpRequest instance is created. Notice the unusual procedure to create this instance in the Internet Explorer in comparison to other browsers.
An anonymous function is attributed to the event req.onreadystatechange, this is the function that will be responsible for dealing with the server reply, which can accessed in the `req.responseText' attribute. This example’s function attributes to the invisible tag’s innerHTML <div id= "synopsis"> </div> the reply obtained from the server.
The method open is then called to set the page to be requested and wether the solicitation is GET or POST. Finally, send method sends the request to the server. The null parameter indicates that no content is being submitted (could be a string or even a DOM object).
It is important to keep in mind that this was an application to exemplify AJAX use and that, in a more elaborate application, instead of the static page, a dynamic page could be requested (such as a PHP or JSP page or a servlet) and a form could be submitted as parameter for the send method.
Where to use AJAX?
Some of the functionalities where AJAX can bring immediate profits to web applications are:
· Data search from a selection box which relies on another, previously selected, selection box. Such as a vehicle prices’ verification application where, depending on the manufacturer of the selected vehicle, a different list of vehicles is shown (example in the next section);
· Validation of forms according to their filling. Notice that, with AJAX, this validation can be made in the server using, for example, information from a database.
· Search of remote content (dictionary, search machines...);
· On-line chat sites, customer supports.
These are only some examples. In fact, after becoming acquainted with AJAX technology, it is hard to imagine a web application that can’t benefit from the asynchronous requests of information.
In this section we will describe, step by step, the construction of a web application that uses AJAX for an asynchronous request of data update from database. The example is developed in JEE (more specifically JSP), using the database MySQL.
This is an application that updates a list of vehicles according to their selected manufacturer, reloading only the vehicle selection box and not the rest of the page.
The first step consists in creating the database’s scheme containing data that can be used by our application. The scheme consists of two tables, manufacturer and car, where the manufacturer table has a 1 to n relationship with the car table. The script in Listing 2 must be loaded into the database, thus creating the tables and the data for the example.
Listing 2. Creating the database.
CREATE TABLE manufacturer (
ID_MANUFACTURER int(10) unsigned auto_increment,
MANUFACTURER varchar(128) NOT NULL default '',
PRIMARY KEY (ID_MANUFACTURER)
insert into manufacturer (MANUFACTURER) values ('Chevrolet');
insert into manufacturer (MANUFACTURER) values ('Fiat');
insert into manufacturer (MANUFACTURER) values ('Ford');
insert into manufacturer (MANUFACTURER) values ('Honda');
insert into manufacturer (MANUFACTURER) values ('Volkswagen');
CREATE TABLE car (
ID_CAR int(10) unsigned auto_increment,
CAR varchar(128) NOT NULL default '',
PRIMARY KEY (ID_CAR)
insert into car (CAR, ID_MANUFACTURER) values ('Celta',1);
insert into car (CAR, ID_MANUFACTURER) values ('Corsa',1);
insert into car (CAR, ID_MANUFACTURER) values ('Astra',1);
insert into car (CAR, ID_MANUFACTURER) values ('Vectra',1);
insert into car (CAR, ID_MANUFACTURER) values ('Uno',2);
insert into car (CAR, ID_MANUFACTURER) values ('Palio',2);
insert into car (CAR, ID_MANUFACTURER) values ('Stilo',2);
insert into car (CAR, ID_MANUFACTURER) values ('Ka',3);
insert into car (CAR, ID_MANUFACTURER) values ('Fiesta',3);
insert into car (CAR, ID_MANUFACTURER) values ('Focus',3);
insert into car (CAR, ID_MANUFACTURER) values ('Fit',4);
insert into car (CAR, ID_MANUFACTURER) values ('Civic',4);
insert into car (CAR, ID_MANUFACTURER) values ('Accord',4);
insert into car (CAR, ID_MANUFACTURER) values ('Gol',5);
insert into car (CAR, ID_MANUFACTURER) values ('Fox',5);
insert into car (CAR, ID_MANUFACTURER) values ('Polo',5);
insert into car (CAR, ID_MANUFACTURER) values ('Passat',5);
Listing 3. Static Page of the model application.
<link rel="stylesheet" href="kalisoftware.css" type="text/css">
<form name="form" id="form">
<font class="title1"> Simplifying AJAX </font>
<p class="content">Only the select box 'Car' will be reloaded.</p>
<select name="manufacturer" onChange="determineCars();">
if (window.ActiveXObject) // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) // not IE
req = new XMLHttpRequest();
var cars = document.getElementById("cars");
cars.innerHTML = req.responseText;
req.open("POST", "LoadCars.jsp", true);
req.send('manufacturer=' + document.form.manufacturer.value);
Notice that this time a parameter is being passed in the send method. For this reason, the content-type of the post was defined in the line immediately above send, so that the parameter could be understood by JSP page LoadCars.jsp.
The responsibility of the JSP page is limited to creating the selection box containing the vehicles of a certain manufacturer set as parameter. It can be made according to Listing 4. Notice that the database search is limited to obtaining the information needed to build the selection box (<select> ... </select>) containing a manufacturer’s vehicles, avoiding unnecessary processes. In a resumed way, in the JSP page, the manufacturer parameter is read (request.getParameter(“manufacturer”);), a connection with the MySQL database is established, and a search among all of the manufacturer’s vehicles is conducted. The vehicles resulting from the database search are then shown as items in the selection box (<option> ... </option>).
Listing 4. JSP page.
<%@ page language="java" import="java.sql.*" errorPage="" %>
// Getting the manufacturer passed as parameter
String manufacturer = request.getParameter("manufacturer");
// Getting a connection to the database
Connection conn = DriverManager.getConnection(
// Selecting the cars of the manufacturer
PreparedStatement pstmt = conn.prepareStatement(
"SELECT * FROM CAR WHERE ID_MANUFACTURER = " + manufacturer);
ResultSet rs = pstmt.executeQuery();
// Listing the cars in the selection box that is going to be returned
The result of accessing the static page in Listing 3 and selecting a manufacturer is shown in Figure 1.
Figure 1. Example Application.
As soon as the user selects a manufacturer, only the vehicles list (highlighted in red) is updated from the data contained in the database, the rest of the page remains unchanged. Thus, in this example, the information flow between browser and applications server is reduced from 2kb (page size) to less than 0,2Kb (selection box size only).
Web applications have been commonly developed in such a manner as to sub-optimize data transfer through the network, with frames or even entire pages being resent from the applications server to the browser every time an interaction with the user occurs. This can give the user the impression of slow and little efficient applications. Several frameworks for web applications development induce this hardly efficient use of this development style (as Struts and JSF). Popular portal construction frameworks, such as the Mambo and the Joomla reach the point of reloading the entire page every time a processing occurs in application server. Beyond performance and user satisfaction questions, there is the question of software engineering itself. After all, to have dynamic pages dealing with several events can result in confused treatments where development anti-patterns become present.
Taking this in consideration, some companies have chosen to build applications with customer-server architecture, where traffic and events can be controlled in a more precise and agile manner (in another hand, the installation of the customer application in the user’s machine becomes necessary, although technologies such as JavaWebStart lighten this impact).
In this article we described an introduction to AJAX, exemplified the construction of web applications using AJAX and presented a component we developed in order to make its use easier.
It is important to emphasize that initiatives have been taken to integrate AJAX to others frameworks (see, for example, the initiative of integration to the JSF, available in https://ajax4jsf.dev.java.net/).
· Ajax: A New Approach to Web Applications: http://adaptivepath.com/publications/essays/archives/000385.php
· AJAX (WEB): http://pt.wikipedia.org/wiki/AJAX_(Web)
· DWR is Easy Ajax for Java: http://getahead.ltd.uk/dwr/
· Java BluePrints AJAX Components: https://blueprints.dev.java.net/ajaxcomponents.html