JavaScript : Ajax

Ajax stands for Asynchronous JavaScript and XML. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. It can send as well as receive information in a variety of formats, including JSON, XML, HTML, and even text files.

The keystone of AJAX is the XMLHttpRequest object. All modern browsers support the XMLHttpRequest object (IE5 and IE6 use an ActiveXObject).  After getting this object , you need to decide what you want to do after you receive the server response to your request. At this stage, you just need to tell the HTTP request object which JavaScript function will handle processing the response. This is done by setting the onreadystatechange property of the object to the name of the JavaScript function that should be called when the state of the request changes, like this:

httpRequest.onreadystatechange = functionToHandleResponse;

Note that there are no parentheses after the function name and no parameters passed, because you’re simply assigning a reference to the function, rather than actually calling it. Also, instead of giving a function name, you can use the JavaScript technique of defining functions on the fly (called “anonymous functions”) and define the actions that will process the response right away, like this:

httpRequest.onreadystatechange = function(){ // process the server response };

To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:“GET”,”ajax_info.txt”,true);
The first parameter of the call t0 open() is the HTTP request method – GET, POST, HEAD or any other method you want to use and that is supported by your server. Keep the method capitalized as per the HTTP standard; otherwise some browsers (like Firefox) might not process the request. For more information on the possible HTTP request methods you can check the W3C specs.

  • The second parameter is the URL of the page you’re requesting. As a security feature, you cannot call pages on 3rd-party domains. Be sure to use the exact domain name on all of your pages or you will get a “permission denied” error when you call open(). A common pitfall is accessing your site by domain.tld, but attempting to call pages with http://www.domain.tld. If you really need to send a request to another domain, see HTTP access control.
  • The optional third parameter sets whether the request is asynchronous. If TRUE (the default), the execution of the JavaScript function will continue while the response of the server has not yet arrived. This is the A in AJAX.
  • send(string) – Sends the request off to the server. string: Only used for POST requests else null.

Remember the ‘functionToHandleResponse‘ setted for httpRequest.onreadystatechange. Let’s see what this function should do. First, the function needs to check for the state of the request. If the state has the value of 4, that means that the full server response has been received and it’s OK for you to continue processing it.

if (httpRequest.readyState === 4) {

// everything is good, the response is received }
else {
// still not ready }

The onreadystatechange event is triggered every time the readyState changes. The readyState property holds the status of the XMLHttpRequest. Three important properties of the XMLHttpRequest object:

Property Description
onreadystatechange Stores a function (or the name of a function) to be called automatically each time the readyState property changes
readyState Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status 200: “OK”
404: Page not found etc.

A server processes an http request and sends out a response. The response comprises a header block, a blank line, and (in most cases) a data block. The first line of the header includes a response code which indicates the success or otherwise of the request – a 3 digit number in the following ranges:

  • 200 and up – success; expect good data to follow
  • 300 and up – good request but only headers (no data). e.g. page has moved
  • 400 and up – error in request. e.g. request was for missing page (404)
  • 500 and up – error in handling request. e.g. program on server has syntax error

Now after you’ve checked the state of the request and the HTTP status code of the response, it’s up to you to do whatever you want with the data the server has sent to you. You have two options to access that data:

  • httpRequest.responseText – returns the server response as a string of text
  • httpRequest.responseXML – returns the response as an XMLDocument object you can traverse using the JavaScript DOM functions

Note that the steps above are only valid if you used an asynchronous request (third parameter of open() as set to true). If you used an synchronous request you don’t need to specify a function, you can access the data return by the server right after calling send(), because the script will stop and wait for the server answer.

Lets see this by an example. In many registration pages, user is asked to have a username for them for future logins. The username is sometimes not available. Lets check the availability using ajax. We would be creating a servlet at the server to handle request.

package mynotes.js.servlets;


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

public class CheckUserNameServlet extends HttpServlet{

String[] usernames={"jane","jake","sam"};
boolean isPresent=false;
String message;

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String input=request.getParameter("username");

for (int i = 0; i < usernames.length; i++) {
message="Username is not available";
message="Username is available";
// Set response content type

// Actual logic goes here.
PrintWriter out = response.getWriter();


As you can see if the input is any of the values in String[] usernames, boolean isPresent will be true and ‘Username is not available’ will be returned. Mapping this servlet in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xsi:schemaLocation="" id="WebApp_ID" version="2.5">




<!DOCTYPE html>
<td>Username: </td>
<td><input type="text" id="username" /></td>
<td><input type="button" id="ajaxButton" onclick="makeRequest();return false" value="Check"/>
<td><div id="result"></div></td>
<script type="text/javascript">

var httpRequest;
function makeRequest() {
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();

if (!httpRequest) {
alert('Cannot create an XMLHTTP instance');
return false;
var url="/MyNotes_JavaScript/CheckUserName?username="+document.getElementById('username').value;
httpRequest.onreadystatechange = processResponse;'GET', url);

function processResponse() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
} else {
alert('There was a problem with the request.');

Notice the url, it should be on the same domail. ‘/’ will append from the domain. If you use just ‘CheckUserName’, it will try to call the current browser url except chagning the last part. (like is is the current url, so it will call instead of callig )




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: