AJAX Tutorial

Asynchronous JavaScript and XML (AJAX) is the art of exchanging data with a live server, and updating parts of a web page – without reloading the whole webpage.

In other words, AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. If an application is not using AJAX, it will have to load a new webpage on every request user made.

In this AJAX tutorial, we will be covering all the necessary and essential facts which enable us to utilize the power of AJAX fully.

Table of Contents

1. How ajax works?
2. Ajax XMLHttpRequest object
3. XMLHttpRequest methods (open(), setRequestHeader(), send(), abort())
4. Synchronous and Asynchronous requests
    - onreadystatechange event, Handling server response
5. Ajax demo
    - Asynchronous example, Synchronous example
6. Popular ajax libraries
    - JQuery, Prototype

1. How ajax works?

It is essential to understand that AJAX is not a single technology but a group of technologies, e.g. HTML, CSS, DOM, and JavaScript, etc. HTML and CSS can be used in combination to mark up and style information of the webpage.

The DOM is accessed with JavaScript to dynamically display the information, and allow the user to interact with, the information presented. JavaScript and the XMLHttpRequest object provide a method for exchanging data asynchronously between the browser and the server to avoid full page reloads.

In recent years, the essence of XML has been reduced. JSON (JavaScript Object Notation) is often used as an alternative format for data interchange, although other formats such as preformatted HTML or plain text can also be used for data purpose.

1.1. AJAX life cycle

Normally, sending an ajax request to the server and getting back the response (life cycle events) from the server involve the following steps:

  • We type the URL of a webpage in the browser’s address bar and hit ENTER. The page is loaded in browser.
  • Some user action triggers an event, like the user clicking a button.
  • Event fires the ajax call, and sends a request to a server.
  • The server takes the input from ajax request, and processes the request. The server also prepare the response if required.
  • The server sends the data back to the webpage that made the request.
  • Another JavaScript function, called a callback function, receives the data in the server response, and updates the web page.

Easy enough, right? Let’s see all the action in the below-given picture.

How AJAX works
How AJAX works?

2. Ajax XMLHttpRequest object

The core of AJAX is the XMLHttpRequest object (available in client side scripting languages like javascript). The XMLHttpRequest object is used to exchange the data with a live server behind the scenes. All modern browsers (IE, Firefox, Chrome, Safari, and Opera) have a built-in XMLHttpRequest object.

If you are using IE 5 or IE6 (I wonder if someone still uses it), then ActiveXObject will be used for server communication to send ajax requests.

2.1. Create XMLHttpRequest object

A new object of XMLHttpRequest is created like this :

//Creating a new XMLHttpRequest object
var xmlhttp;
if (window.XMLHttpRequest)
{
	xmlhttp = new XMLHttpRequest(); //for IE7+, Firefox, Chrome, Opera, Safari
}
else
{
	xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //for IE6, IE5
}

This xmlhttp variable can be re-used to send multiple ajax requests, without creating a new object for each request.

XMLHttpRequest is subject to the browser’s same origin policy for security reasons. It means that a request will only succeed if it is made to the same origin server that served the webpage.

3. XMLHttpRequest methods

To send requests and set request attributes, XMLHttpRequest object provides following methods:

3.1. open(method, url, isAsync, userName, password)

The HTTP and HTTPS requests of the XMLHttpRequest object must be initialized through the open() method. open() specifies the type of request (GET, POST etc.), the request URL, and if the request should be handled asynchronously or not.

The 4th and 5th parameters are the username and password, respectively. These parameters can be provided for authentication and authorization purposes if the server needs it.

	xmlhttp.open("GET","report_data.xml",true);

	xmlhttp.open("GET","sensitive_data.xml",false);

	xmlhttp.open("POST","saveData",true,"myUserName","somePassord");

The open() method:

  • throws a “SyntaxError” if either method is not a valid HTTP method or url cannot be parsed.
  • throws a “SecurityError” if method is a case-insensitive match for ‘CONNECT’, ‘TRACE’, or ‘TRACK’.

3.2. setRequestHeader(name, value)

Upon successful initialization of a request, the setRequestHeader() method of the XMLHttpRequest object can be invoked to set HTTP headers in the request.

//Tell the server that this call is made for ajax purposes.
xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');  
xmlhttp.setRequestHeader('X-Test', 'some-value');

The setRequestHeader() method:

  • throws a “InvalidStateError” if either state is not opened or the send() flag is set.
  • throws a “SyntaxError” if name is not a header name or if value is not a header value.

3.3. send(payload)

To finally send an HTTP request, the send() method of the XMLHttpRequest must be invoked. This method accepts a single parameter containing the request body to be sent with the request.

The payload is necessary in POST requests. For GET and HEAD methods, simply pass null as a parameter.

	xmlhttp.send(null); //HTTP GET

	xmlhttp.send( '{"id":"23423"}' ); //HTTP POST

The send() method throws an “InvalidStateError” if either state is not opened or the send() is already invoked and response has not been received yet.

3.4. abort()

It aborts the request if the readyState of the XMLHttpRequest object has not yet become 4 (request complete). The abort() method ensures that the callback method does not get invoked in an asynchronous request.

//Abort the processing
xmlhttp.abort();

Apart from above methods, onreadystatechange() event listener is very important which we will discuss in the next section.

4. Asynchronous and Synchronous AJAX Requests

XMLHttpRequest object is capable of sending synchronous and asynchronous requests, as required from the webpage. This behavior is controlled by the third parameter of open() method.

This parameter is set to:

  • true – asynchronous requests
  • false – synchronous requests
//Asynchronous request as third parameter is true
xmlhttp.open("GET", "report_data.xml", true); 

//Synchronous request as third parameter is false
xmlhttp.open("GET", "report_data.xml", false); 

The default value is true if it is not provided.

Asynchronous AJAX Requests do not block the webpage, and the user can continue to interact with the other elements on the page while the server is processing the request.

We should always use asynchronous AJAX requests because a synchronous AJAX Request makes the UI (browser) unresponsive. It means the user will not be able to interact with the webpage until the request is complete.

Synchronous requests should be used in rare cases with utmost care. For example, synchronous AJAX requests should be used if we’re embedding a new JavaScript file on the client UI using AJAX and then referencing types and objects from that JavaScript file. Then the fetching of this new JS file should be included through using a synchronous AJAX Request.

4.1. Synchronous AJAX Request Example

Given below is a JavaScript program to show how to make synchronous requests with AJAX.

var request = new XMLHttpRequest();
request.open('GET', '/bar/foo.txt', false);  //"false" makes the request synchronous
request.send(null);

if(request.status === 200) 
{
	//request successful; handle the response
}
else
{
	//Request failed; Show error message
}

4.2. Asynchronous AJAX Request Example

Given below is a JavaScript program to show how to make asynchronous requests with AJAX.

var request = new XMLHttpRequest();
request.open('GET', '/bar/foo.txt', true);  //"true" makes the request asynchronous

request.onreadystatechange = function() {
	if (request.readyState == 4) { 
		if (request.status == 200) 
		{
			//request succeed
		} 
		else
		{
			//request failed
		}
	}
};

request.send(null)

4.3. onreadystatechange Event

In the above example, onreadystatechange is an event listener registered with XMLHttpRequest request. onreadystatechange stores a function that will process the response returned from the server.

The function will be called for all important events in request’s life cycle. Every time an step is completed in request processing, the value of readyState property will be changed and set to one of the given integer values:

  • 0 : request is not initialized
  • 1 : server connection established
  • 2 : request received
  • 3 : processing request
  • 4 : request finished and response is ready to be handled

4.4. Handling Response From Server

To fetch the response sent from the server, responseText or responseXML property of the XMLHttpRequest object is used. If the response from the server is XML, and you want to parse it as an XML object, use the responseXML property. If the response from the server is not XML, use the responseText property.

  • responseText : Get the response from server as a string
  • responseXML : Get the response from server as XML

Given below is a JavaScript program that fetches the response sent from the server for an AJAX request.

if (xmlhttp.readyState == 4) { 
	if (xmlhttp.status == 200) 
	{
		document.getElementById("message").innerHTML = xmlhttp.responseText;
	} 
	else {
		alert('Something is wrong !!');
	}
}

5. AJAX Demo

For demonstration purposes, we are creating a hello world application. In the application, the webpage sends an AJAX request HTTP GET request to query the current server’s system time. In response, the server sends the present time. Easy enough.

ajax demo application

5.1. Asynchronous AJAX Request

To enable the webpage to send asynchronous request, I have written following javascript code in JSP page:

function ajaxAsyncRequest(reqURL)
{
	//Creating a new XMLHttpRequest object
	var xmlhttp;
	if (window.XMLHttpRequest){
		xmlhttp = new XMLHttpRequest(); //for IE7+, Firefox, Chrome, Opera, Safari
	} else {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //for IE6, IE5
	}

	//Create a asynchronous GET request
	xmlhttp.open("GET", reqURL, true);
	
	//When readyState is 4 then get the server output
	xmlhttp.onreadystatechange = function() 
	{
		if (xmlhttp.readyState == 4) 
		{ 
			if (xmlhttp.status == 200) 
			{
				document.getElementById("message").innerHTML = xmlhttp.responseText;
				//alert(xmlhttp.responseText);
			} 
			else
			{
				alert('Something is wrong !!');
			}
		}
	};
	
	xmlhttp.send(null);
}

And to fire the ajax request, an HTML button should be clicked which is written as:

<input type="button" value="Show Server Time" 
	onclick='ajaxAsyncRequest("get-current-time")'/>

To handle the request on server side, I have written a servlet like this:

public class GetTimeServlet extends HttpServlet 
{
	private static final long serialVersionUID = 1L;

	public void doGet (HttpServletRequest request,HttpServletResponse response) 
			throws ServletException, IOException 
	{
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		PrintWriter out = response.getWriter();
		Date currentTime= new Date();
		String message = String.format("Currently time is %tr on %tD.",currentTime, currentTime);
		out.print(message);
	}
}

The above code will return the current server time in response in text form, which client code receives and prints on the webpage.

ajax demo application success

5.2. Synchronous AJAX Request

To send synchronous ajax request, change the javascript code in index.jsp file with this:

function ajaxSyncRequest(reqURL)
{
	//Creating a new XMLHttpRequest object
	var xmlhttp;
	if (window.XMLHttpRequest){
		xmlhttp = new XMLHttpRequest(); //for IE7+, Firefox, Chrome, Opera, Safari
	} else {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //for IE6, IE5
	}
	//Create a asynchronous GET request
	xmlhttp.open("GET", reqURL, false);
	xmlhttp.send(null);
	
	//Execution blocked till server send the response
	if (xmlhttp.readyState == 4) { 
		if (xmlhttp.status == 200) 
		{
			document.getElementById("message").innerHTML = xmlhttp.responseText;
		} 
		else
		{
			alert('Something is wrong !!');
		}
	}
}

You do not need to check the ready state in synchronous requests because the response will be available only when the request completes. Till the time, the page will be blocked.

6. Popular AJAX Libraries

As it is evident that AJAX is a prevalent technology nowadays for making web pages highly interactive and user friendly. Various UI frameworks are available for developers in the market today, which use AJAX for faster and secure development. The good thing is that they all are free to use.

6.1. AJAX with JQuery

JQuery is probably the most popular among its alternatives. It has got its own developer community, which is highly active also. A sample code for sending ajax request using jquery will be like is:

//Current request reference; can be used elsewhere
var request;

/* attach a submit handler to the form */
$("#buttonId").submit(function(event) {

	// abort any pending request
    if (request) {
        request.abort();
    }
	
  /* stop form from submitting normally */
  event.preventDefault();

  /*clear result div*/
   $("#result").html('');

  /* get some values from elements on the page: */
   var values = $(this).serialize();

  /* Send the data using post and put the results in a div */
  request =$.ajax({
      url: "ajaxRequest",
      type: "post",
      data: values,
      success: function(){
           $("#result").html('submitted successfully');
      },
      error:function(){
          $("#result").html('there is error while submit');
      }   
  }); 
});

6.2. AJAX with Prototype

Prototype is another popular framework for the same purpose. But, please beware that prototype is known to be incompatible with some other frameworks. A example code for sending ajax request using prototype will look like this:

new Ajax.Request('/some_url',
 {
	method:'get',
	onSuccess: function(transport) 
	{
		var response = transport.responseText || "no response text";
	},
	onFailure: function() 
	{ 
		alert('Something went wrong...'); 
	}
});

That’s all for this AJAX tutorial. Please share your feedback.

Happy Learning !!

Leave a Reply

56 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial