Introduction
Once I was working on a web project using JSPs and Java and I needed to implement the AJAX. At that time, I had just heard the name of AJAX technology. As usual, the time line was very short, so I searched some good PDF books on AJAX. I opened the books and it increased my worries because these were too lengthy and I thought that I might not be able to read some basic chapters in that short span of time. Anyhow after some skimming and scanning of large materials, I was able to implement AJAX.
I think this article will be very helpful for the beginners of AJAX. I hope that after completing this article, you people will be able to implement AJAX in your applications as well.
AJAX is an acronym for Asynchronous JavaScript And XML.
AJAX is not any new programming language, but simply a new technique for creating better, faster, and more interactive web applications. AJAX uses JavaScript to send and receive data between a web browser and a web server.
The AJAX technique makes web pages more responsive by exchanging data with the web server behind the scenes, instead of reloading an entire web page each time a user makes a change. The best example of AJAX implementation is Yahoo mails. Another example of AJAX implementation is populating the city and state based upon the zip entered in a TextBox or partial page update.
It uses asynchronous data transfer (HTTP requests) between the clients browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages to be reloaded.
Bases of AJAX
AJAX is very simple technology based on the following open standards:
The open standards used in AJAX are supported by all major browsers. AJAX applications are browser and platform independent. You can say it is a Cross-Platform and Cross-Browser technology at the same time. A traditional web application usually submits its input (using an HTML form) to a web server. After the web server has processed the data/request, it will return a completely new web page to the user’s browser.
Because the server returns a new web page each time the user submits input, traditional web applications often run slowly and tend to be less user friendly.
With AJAX, web applications can send and retrieve data without reloading the whole web page. This is done by sending HTTP requests to the server (behind the scenes), and by modifying only parts of the web page using JavaScript when the server returns data.
The back bone of the AJAX technology is the XMLHttpRequest
object.
To create AJAX web applications, you have to become familiar with the JavaScript object called the XMLHttpRequest
.
The XMLHttpRequest
The XMLHttpRequest
object is the key to AJAX. It has been available ever since Internet Explorer 5.5 was released, but not fully discovered before people started to talk about AJAX and Web 2.0 in 2005.
It is very simple to create an XMLHttpRequest
object like:
available in Internet Explorer 6 and later
var XMLHttp=new ActiveXObject("Msxml2.XMLHTTP")
available in Internet Explorer 5.5
var XMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
built in JavaScript object available in almost all of the Internet Explorers.
var XMLHttp=new XMLHttpRequest()
Methods Available with XMLHttpRequest
The open() Method
The open()
method sets up a request to a web server.
The send() Method
The send()
method sends a request to the server. (Behind the scene. Client’s browser does not refresh or takes any round trip.)
The abort() Method
The abort()
method aborts the current server request.
ReadyState Property of XMLHttpRequest
The readyState
property defines the current state of the XMLHttpRequest
object. Here are the possible values for the readyState
property:
State | Description |
readyState=0
| The request is not initialized. After you have created the XMLHttpRequest object, but before you have called the open() method.
|
readyState=1
| The request has been set up. After you have called the open() method, but before you have called send() .
|
readyState=2
| The request has been sent. After you have called send() .
|
readyState=3
| The request is in process. After the browser has established a communication with the server, but before the server has completed the response.
|
readyState=4
| The request is completed. After the request has been completed, and the response data have been completely received from the server.
|
For your AJAX applications, you will actually only be interested in state 4, i.e., when the request is completed and it is safe to use the received data.
After this basic and precise knowledge of XMLHttpRequest
, now you are able to implement the AJAX technology. How simple it is! Isn't it?
Using the Code
There are three code files. One holding the JavaScript code, the second holding your front end HMTL code and the third one has the server side code that will be executed behind the scenes to the client and will give back response to the front-end HTML page through the JavaScript file.
Step 1-Place the Following Code in your HTML File
<html>
<head>
<script src="getEmployee.js"></script>
</head><body><form>
Select a Employee:
<select name="Employees" onChange="showEmployee(this.value)">
<option value="SABAH">Sabah u din
<option value="HASAN">Hasan Tanvir
<option value="MUZIO">Muzaffar Iqbal
<option value="YASIR">Yasir Siddiq
<option value="WAQAS">Waqas u Din
</select>
</form>
<div id="EmployeesDIV"><b>Employees info will be listed here.;)</b></div>
</body>
</html>
Step 2. Make a JavaScript file using the Following Code
var xmlHttp
function showEmployee(str)
{
xmlHttp=CreateXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="GetEmployeeInfo.jsp"
url=url+"?qparam="+str
url=url+"&sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("EmployeesDIV").innerHTML=xmlHttp.responseText
}
}
function CreateXmlHttpObject()
{
var objXMLHttp=null
if (window.XMLHttpRequest)
{
objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}
Step 3. Make a Server Side Page (JSP/ASP/PHP/...)
As I am using it with JSP, I am providing you the example page in JSP code. You can change this code according to your requirement of the server side programming language like PHP, ASP, etc. or any other you are working in. Just remember to include the correct name of this file with extension in the showEmployee()
function of JavaScript where you are building a URL to hit behind the scene.
Here is the code in JSP. Save it with the name GetEmployeeInfo.jsp.
// File GetEmployeeInfo.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String responseText=new String("");
String OptionValue=(String) request.getParameter("qparam");
responseText="<table width=\"200\" border=\"1\"><tr> <td>Name</td>
<td>Designation</td> <td>Age</td></tr>";
if(OptionValue==null){OptionValue="NULL";}
if(OptionValue.equals("SABAH"))
{
responseText+="<tr> <td>1610</td>
<td>Software Engineer </td>
<td>22</td> </tr>";
}
else if (OptionValue.equals("HASAN"))
{
responseText+="<tr> <td>1592</td>
<td>System Engineer </td> <td>24</td> </tr>";
}
else if (OptionValue.equals("MUZIO"))
{
responseText+="<tr> <td>1598</td>
<td>Graphic Designer </td> <td>25</td> </tr>";
}
else if (OptionValue.equals("YASIR"))
{
responseText+="<tr> <td>1626</td>
<td>Network Engineer </td> <td>23</td> </tr>";
}
else if ( OptionValue.equals("WAQAS"))
{
responseText+="<tr> <td>1595</td>
<td>Recuiter </td> <td>19</td> </tr>";
}
else
{
responseText+="<tr> <td>N/A</td> <td>N/A</td> <td>N/A</td> </tr>";
}
responseText+="</table> ";
out.print(responseText);
%>
</body>
</html>
In the above server side code, you can either get the values from the data base (MYSQL, Microsoft SQL Server 2005, Oracle, Microsoft Access, XML). Just one thing to keep in mind that you have to make a valid HTML and send it to the Response
of that page.
Browser Support
AJAX applications can only run in web browsers with complete XML support. Internet Explorer (IE) and Mozilla Firefox have complete enough support for XML to run AJAX applications.
History
- 12th December, 2006: Initial post