Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Simplifying AJAX

Simplifying AJAX

Simplifying AJAX

 

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?

The acronym AJAX stands for “Asyncronous Javascript And XML”. A definition found for AJAX was: “The systemic use of Javascript and XML to make web applications more interactive, using asynchronous requests of information”.

The main idea behind AJAX is to make web applications more dynamic and creative. To achieve this, it makes use of not only a technology, but of a set of technologies working together. Basically they are: XHTML, CSS, DOM, XML, XSLT, XMLHttpRequest and JavaScript (the latter playing the role of bringing together all of the former). AJAX is supported by various browsers (as Mozilla Firefox, Internet Explorer 5+, Opera, Konqueror or Safari).

Did the number of technologies scare you? Don’t be discouraged, everything spins around the old and well known Javascript. For the sake of disallowing greater doubts, here follow brief descriptions of the other technologies involved:

·         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.

·         XMLHttpRequest: Javascript object used for the asynchronous recovery of data. Further details on this object will be seen along the paper.

 

How to use AJAX in a web application?

The use of AJAX consists in, based on an action in the page, requesting a Javascript function that creates a XMLHttpRequest object; sends this function to the server through GET or POST; the server then returns the result to Javascript itself which, in turn, based on this reply, performs some action.

The server’s reply can be in plain text or XML. In the first case, data is simply inserted in some exhibition page’s object XHTML content (innerHTML). In the second case, it is possible to work the XML data using Javascript.

An example of functionality that could benefit from AJAX is in a list of movie titles where, when clicking on one of the movies, the objective is to show the user the movie’s summary. In this case, a table with the list of the films is created. When you click on a movie a Javascript function is called to get the movie summary in the server using AJAX and showing it in another of the page’s fields (see Table 1). This example, which demands a static page (mov1.HTML, mov2.HTML, mov3.HTML or mov4.HTML) from the applications’ server is demonstrated below.

 

Available Movies

Synopsis

The Perfect Plan

image001.jpg

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).
129 min. – Restriction 14 Years Old.

Red Carpet

V for Vendetta

Mission Impossible III

Table 1. Application Example.

 

The “searchForSynopsis(idMovie)” Javascript function code called upon in the onClick event of each cell with the movie title is shown in Listing 1.

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();

       

        req.onReadyStateChange=function()

        {

            if (req.readyState==4)

            {

                var synopsis = document.getElementById("synopsis");

                synopsis.innerHTML = req.responseText;

            }

        }

       

        req.open("GET", "movie" + idMovie + ".html", true);

        req.send(null);

    }

 

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.

Case study

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,

  ID_MANUFACTURER int(10),

  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);     

 

Once our scheme has been created, we can develop our example application. It is composed of two pages, one of them static, the other, dynamic (JSP). The static page will contain both selection boxes (manufacturers and vehicles) and will make use of AJAX to search the JSP page and update the vehicle selection box (only the vehicle selection box) when the manufacturer selection box is modified (in the ‘select’ ‘onChange’ event). The static page containing the javascript that use AJAX is found in Listing 3.

Listing 3. Static Page of the model application.

<html>

<head>

         <link rel="stylesheet" href="kalisoftware.css" type="text/css">

         <title>Simplifying AJAX</title>

</head>

 

<body>

  <form name="form" id="form">

    <font class="title1"> Simplifying AJAX </font>

    <br> 

    <p class="content">Only the select box 'Car' will be reloaded.</p>   

    <p class="content">Manufacturer:</p>

    <select name="manufacturer" onChange="determineCars();">   

      <option></option>

      <option value="1">Chevrolet</option>

      <option value="2">Fiat</option>       

      <option value="3">Ford</option>

      <option value="4">Honda</option>

      <option value="5">Volkswagen</option>           

    </select>  

    <br>

    <p class="content">Car:</p>     

    <div id="cars">   

      <select name="car">   

      </select>

    </div> 

  </form>

</body>

</html>

 

<script>

  function determineCars()

  {

    if (window.ActiveXObject) // IE

      req = new ActiveXObject("Microsoft.XMLHTTP");

    else if (window.XMLHttpRequest) // not IE

      req = new XMLHttpRequest();          

   

    req.onReadyStateChange=function()

    {

      if (req.readyState==4)

      {

        var cars = document.getElementById("cars");

        cars.innerHTML = req.responseText;

      }

    }

 

    req.open("POST", "LoadCars.jsp", true);

    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    req.send('manufacturer=' + document.form.manufacturer.value);

  }

</script>

 

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="" %>

<select>

<%

  // Getting the manufacturer passed as parameter

  String manufacturer = request.getParameter("manufacturer");

 

  try

  {

    // Getting a connection to the database

    Class.forName("com.mysql.jdbc.Driver").newInstance();

    Connection conn = DriverManager.getConnection( 

                            "jdbc:mysql://localhost:3306/AJAX?user=root&password="coppe");

 

    // 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

    while(rs.next())

    {

%>

      <option><%= rs.getString("CAR")%></option> 

<%

    }

    rs.close();

  }

  catch(Exception e)

  {

    e.printStackTrace();

  }

%>

</select>

 

The result of accessing the static page in Listing 3 and selecting a manufacturer is shown in Figure 1.

 

image003.jpg

image005.jpg

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).

Final analysis

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).

AJAX is a step towards allowing web applications to have this control and agility, making the browser  to cease to be “customer-zero” and making itself more present, after all it’s in the browser that we execute Javascript and it’s in that the XMLHttpRequest object is loaded in memory. Events are then able to be dealt with in the browser, making use of the processes that occur in the applications server.

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/).

References

·         Ajax: A New Approach to Web Applications: http://adaptivepath.com/publications/essays/archives/000385.php

·         AJAX (WEB): http://pt.wikipedia.org/wiki/AJAX_(Web)

·         Asynchronous JavaScript Technology and XML (AJAX): http://java.sun.com/developer/technicalArticles/J2EE/AJAX/

·         DWR is Easy Ajax for Java: http://getahead.ltd.uk/dwr/

·         Java BluePrints AJAX Components: https://blueprints.dev.java.net/ajaxcomponents.html



colunista nao disponivel

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login