You are on page 1of 5

Getting Started with AJAX using Java

AJAX is an acronym for Asynchronous JavaScript And XML. AJAX provides an ability to
communicate with the server asynchronously. Here asynchronous is the keyword. To explain that in
simple terms, you can send a request to server and continue user interaction with the user. You need not
wait for response from the server. Once the response arrives, a designated area in UI will update itself
and reflect the response information. Whole page need not be reloaded.
This is achieved by AJAX using XMLHttpRequest object. Your browser provides the capability for
XMLHttpRequest object. Most modern browsers provides support for XMLHttpRequest. This object
helps for http request and process XML response. It is not mandatory that you should use only XML.
Simple text can also be used in Ajax but which is uncommon.
Before continuing with the article, I assume that you have basic knowledge about http headers, request
response mechanism, different method types and response codes. If you lack knowledge in these areas,
it is better to update them before proceeding. If you cant read GET, POST, HTTP status 200 OK and
response Content-Type: text/html, xml then you must know these topics before learning AJAX. I am
not writing in detail about them here, because each one of them calls for a detailed separate article.
Let me write a HelloWorld ajax web application to demonstrate basics. We shall have a button with
name ‘Say Hello!’ On click of that button, without reloading the whole page we will display “Hello
World!” by replacing the ‘Say Hello!’ button. Following source code listing contains complete code of
sample web application.

<html xmlns="">
<title>Getting Started with AJAX using JAVA</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"
<script type="text/javascript" language="javascript"
<div>Getting Started with AJAX using JAVA: Hello World!</div>
<div id="hello"><button type="button" onclick="makeRequest()">Say
index.jsp contains a div ‘hello’. That is the div which XMLHttpRequest object is going to overwrite
with response from Servlet. On click of the button we call a java script function makeRequest(). Until
now, there is nothing special. Its usual jsp and javascript call. Ajax is not in the picture.
Now go through makeRequest() given below. Inside that we call getXMLHttpRequest() which returns
a XMLHttpRequest object. That can be used as a utility method in all your AJAX programs. Thats an
attempt to standardization. Different versions of browsers provide different ways of creating
XMLHttpRequest. We are covering all possible combinations inside that method.
Once we get XMLHttpRequest object, we need to register a function which will be called on state
change. Now its time to explain in detail about XMLHttpRequest object.

XMLHttpRequest properties and events

XMLHttpRequest consists of properties readyState, status, statusText, responseText and
• readyState denotes states as 0 – UNINITIALIZED, 1 – LOADING, 2 – LOADED, 3 –
• status is HTTP status code for the response
• statusText is HTTP status message for the status code
• responseText is response text from server
• responseXML is DOM document object of reponse XML document from server
XMLHttpRequest contains an event ‘onreadystatechange’. It is invoked whenever ‘readyState’
property given above changes.
We need to register a function for the above event ‘onreadystatechange’. In our makeRequest(), after
getting xmlHttpRequest object we register getReadyStateHandler(xmlHttpRequest). Therefore
whenever there is a state change, this function will be called by the XMLHttpRequest / browser.
After registering the callback funtion we set the request url as the HelloWorld servlet. In web.xml we
have done the servlet mapping for that servlet.
In getReadyStateHandler function, if readyState is 4 and http status code is 200 then we set the reponse
text from XMLHttpRequest object to the div hello in index.jsp.

* creates a new XMLHttpRequest object which is the backbone of
* or returns false if the browser doesn't support it
function getXMLHttpRequest() {
var xmlHttpReq = false;
// to create XMLHttpRequest object in non-Microsoft browsers
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
// to create XMLHttpRequest object in later versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
// to create XMLHttpRequest object in older versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
return xmlHttpReq;
* AJAX call starts with this function
function makeRequest() {
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange =
getReadyStateHandler(xmlHttpRequest);"POST", "", true);

* Returns a function that waits for the state change in
function getReadyStateHandler(xmlHttpRequest) {

// an anonymous function returned

// it listens to the XMLHttpRequest instance
return function() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
document.getElementById("hello").innerHTML =
} else {
alert("HTTP error " + xmlHttpRequest.status + ": " +
A simple Hello World servet sending response as Hello World! as text.
package com.javapapers.sample.ajax;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet {

* A simple HelloWorld Servlet
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws {
res.getWriter().write("Hello World!");

public void doGet(HttpServletRequest req, HttpServletResponse res)

throws {
doPost(req, res);

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=""
xsi:schemaLocation="" id="WebApp_ID"
<display-name>Getting Started with AJAX using JAVA</display-name>

Output of Hello World AJAX

Before AJAX call:
After AJAX call:
I have used text response to demonstrate AJAX. There is a lot more to AJAX. I will get into using
XML, advanced techniques and jquery in future articles.