Original URL: http://www.theregister.co.uk/2006/06/09/ajax_web_tutorial/

Introduction to Developing Web Applications with AJAX - Part 1

There’s a better way of filling out web forms…

By Deepak Vohra

Posted in Developer, 9th June 2006 08:04 GMT

How often have you found yourself filling out a web form requiring umpteen fields to be specified which, when you submit the form, returns the message, “Invalid input” or “Field value not valid”?

Asynchronous JavaScript And XML (AJAX) provides a method for the completion and validation of web forms. It’s a web technique for developing asynchronous web applications using JavaScript, Document Object Mode (DOM) and XMLHttpRequest technologies. AJAX provides dynamic interaction between a client and a server and has various applications, such as:

JavaScript and XML DOM technologies are relatively established technologies so we won’t discuss them further here. XMLHttpRequest, however, is a relatively new technology and merits discussion.

Overview of XMLHttpRequest

The XMLHttpRequest object provides asynchronous communication between web applications and underlying servers and business services. Using the object, clients may submit XML data to, and retrieve it from, a web server without reloading the page. XML data may be converted to HTML on the client side, using DOM and Extensible Style sheet Transformations (XSLT).

XMLHttpRequest was introduced by Microsoft with Internet Explorer 5 as an ActiveX object. Most browsers support XMLHttpRequest, however, the implementations are usually not interoperable. For example, an instance of an XMLHttpRequest object is created in IE 6 with code shown in following listing:

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

However, in Internet Explorer 7, XMLHttpRequest is available as a window object property. An instance of XMLHttpRequest object in IE 7 is created as shown here:

var req = new XMLHttpRequest();

Recently, W3C has introduced a Working draft of the XMLHttpRequest object, which will standardize implementations of the XMLHttpRequest object.

The XMLHttpRequest object has various attributes/properties and methods to provide HTTP client functionality; its properties are presented in Table 1.

Table 1. XMLHttpRequest Properties

Property Description
onreadystatechange Sets the callback method for asynchronous requests
readyState Retrieves the current state of a request. 0-XMLHttpRequest object has been created. 1-The object has been created and the open() method has been invoked. 2-The send() method has been called, but the response has not been received. 3-Some data has been received that is available in the responseText property. responseXML produces null and response headers and status are not completely available. 4-Response has been received.
responseText Retrieves the text of response from server.
responseXML Retrieves the XML DOM of response from server.
status Retrieves the HTTP status code of request. For status code definitions refer to here.
statusText Retrieves the status text of the HTTP request.

XMLHttpRequest object methods are used to open an HTTP request, send the request and receive the response. These methods are presented in Table 2.

Table 2. XMLHttpRequest Methods

Method Description
abort() Cancels the current HTTP request.
getAllResponseHeaders() Gets all the response headers. readyState is required to be 3 or 4 to retrieve the response headers.
getResponseHeader(string header) Gets a specified response header. readyState is required to be 3 or 4 to retrieve a response header.
open(string method, string url, boolean asynch, string username, string password) Opens a HTTP request. Does not send a request. readyState property gets set to 1. responseText, responseXML, status, and statusText properties get reset to their initial values. The HTTP method and server URL, which may be relative or absolute, are required parameters. Boolean parameter asynch specifies if HTTP request is asynchronous. Default value is true. Username and password are optional.
<send(data) Sends a HTTP request to the server, including data, which may be a string, an array of unsigned bytes, an XML DOM object, or null. The send() method is synchronous or asynchronous corresponding to the value of the asynch argument in the open() method. If synchronous, the method does not return until the request is completely loaded and the entire response has been received. If asynchronous, method returns immediately. The readyState property gets set to 2 after invoking the send() method. The readyState property gets set to 4 after the request has completed loading.
setRequestHeader(string headerName, string headerValue) Sets HTTP request headers.

Installing Software

AJAX being a web technique, not a technology, does not in itself require any additional software other than a browser that supports the XMLHttpRequest object. If not already installed, we need to install a web browser, such as Internet Explorer (IE) 7, or IE 6, or Netscape 6+.

To develop an AJAX web application, however, we need a web/application server. Therefore, we download and install JBoss 4.0.2. We also need to install the J2EE 1.4 SDK. We then need to copy the lib/j2ee.jar JAR file from the J2EE 1.4 installation to the server/default/lib directory of the JBoss installation.

The AJAX application that we will develop retrieves data from a database. So, we need to install a relational database such as the open source database MySQL 5.0 (from here), which is used for this article. Finally, we’ll need the MySQL JDBC driver Connector/J.

Configuring JBoss with MySQL Database

We now need to create a MySQL database user. To do this we login to the MySQL database using following command:

mysql --user=root mysql

A new user may be added to the user table with an GRANT statement as shown below (as an example, we’re creating a user 'mysql' with password 'mysql'):

GRANT ALL PRIVILEGES ON test TO 'mysql'@'localhost'

We also need to create an example table in the MySQL database. To create a table, login to the database as mysql user and run the SQL script catalog.sql from the Resources zip file here.

Next we configure the JBoss application server with the MySQL database. To do this, we first need to copy the MySQL driver classes into the classpath.

Copy the JAR file mysql-connector-java-3.1.11-bin.jar to the <jboss-4.0.2>/server/default/lib directory. <jboss-4.0.2> is the directory in which JBoss 4.02 is installed.

To use the MySQL data source, copy <jboss-4.0.2>/docs/examples/jca/mysql-ds.xml to the <jboss-4.0.2>/server/default/deploy directory.

Modify the mysql-ds.xml configuration file by setting <driver-class/>to com.mysql.jdbc.Driver and <connection-url/> to jdbc:mysql://localhost:3306/test.

In mysql-ds.xml also specify user-name as mysql and password as mysql. The jndi-name is set to MySqlDS by default. The mysql-ds.xml file is available in the Resources zip file here.

We also need to modify the <jboss-4.0.2>/server/default/conf/login-config.xml with MySQL database settings. Add the <application-policy/> element in resource file login-config.xml to login-config.xml.

Once the mysql-ds.xml and login-config.xml files have been modified, the JBoss 4 server is configured for use with a MySQL database.

Creating an Eclipse Project

Now we can start to develop an actual web application using the AJAX technique. To compile and run the web application, we create an Eclipse project. We then create web application files, and add them to the Eclipse project. We will create the required AJAX application files in a src folder and import the folder to the src folder of the project. So, create a src folder in a directory and add files build.xml, inputForm.jsp, error.jsp</em, and catalog.jsp from the Resources zip file to the src folder.

Create a WEB-INF folder in the src folder. Add web application deployment descriptor, web.xml, from the Resources zip file to the WEB-INF folder. Add a classes folder to the WEB-INF folder. Copy FormServlet.java from the Resources zip file to the classes folder.

In the Eclipse project, we will compile and deploy the AJAX application using a build.xml file, from the Resources zip file.

We import the src folder to the src folder in the Eclipse project, which we have already created. To import the src folder, select the src folder in the Eclipse project in Package Explorer and choose File>Import. In the Import frame, select File System and select Next. Then, select the src folder in the File System frame and select Finish. The src folder gets added to the src folder in the Eclipse project.

In the Eclipse project, set JRE system library to JRE 5.0. To compile the servlet application in the web application, add j2ee.jar to the Java Build Path of the Eclipse project. Next, select targets in the Ant build.xml file that will run to compile and deploy the AJAX web application. Right-click on the build.xml file and select Run As and select the second Ant Build selection. Select the Targets frame in the build.xml frame. Select the checkboxes for the init, compile, and webapp targets and click on the Apply button.

Next, we will run the Ant build.xml file to compile our AJAX web application and deploy it to the JBoss application server. Right-click on build.xml in the Package Explorer and select Run As and the first Ant build.xml selection. The Ant build.xml script runs and compiles; and then compiles and deploys the AJAX web application to the JBoss application server.

We will discuss the detail of the AJAX web application in the next article in this series. ®