Complete AJAX tutorial

Asynchronous JavaScript and XML (AJAX) is the art of exchanging data with a 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 application are not using AJAX, then it will have to reload the webpage on every request user made.

Ads by Google

In this tutorial, I will be covering all basic and important facts you should know before working on ajax based application, to fully utilize the power of ajax.

Sections in this post

How ajax works?
Ajax request and response objects
    - Useful methods (open(), setRequestHeader(), send(), abort())
Synchronous and Asynchronous requests
    - onreadystatechange event, Handling server response
Demo application
    - Asynchronous example, Synchronous example
Some popular ajax capable libraries
    - JQuery, Prototype
Download source code

How ajax works?

It is important 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. The DOM is accessed with JavaScript to dynamically display, and allow the user to interact with, the information presented. JavaScript and the XMLHttpRequest object provide a method for exchanging data asynchronously between browser and server to avoid full page reloads.

In recent years, 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.

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

  • You type the URL of a webpage in browser’s address bar and hit enter. Page is loaded in browser window.
  • Some action triggers an event, like the user clicking a button.
  • Event fires the ajax call, and sends a request to a server using xml or json.
  • The server service takes the input from ajax/http request, and processes the request. It also prepare the response data if required.
  • Server sends the data back to the original webpage that made the request.
  • Another JavaScript function, called a callback function, receives the data, and updates the web page.

Easy enough, right? Lets see all the action in below given picture.

How AJAX works

How AJAX works?

Ajax request and response objects

The core of AJAX is the XMLHttpRequest object (available in client side scripting languages like javascript). The XMLHttpRequest object is used to exchange data with a server behind the scenes. All modern browsers (IE7+, 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.

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 new objects. XMLHttpRequest is subject to the browser’s same origin policy for security reasons. It means that requests will only succeed if they are made to the same server that served the original web page.

Useful methods to work with XMLHttpRequest

To send request and set request attributes, XMLHttpRequest object has some methods. Lets have a look onto them:


a) open(method, url, isAsync, userName, password)

The HTTP and HTTPS requests of the XMLHttpRequest object must be initialized through the open method.  This method specifies the type of request (GET, POST etc.), the URL, and if the request should be handled asynchronously or not. I will cover this third parameter in next section.

The fourth and fifth parameters are the username and password, respectively. These parameters, or just the username, may be provided for authentication and authorization if required by the server for this request.

Example:

	xmlhttp.open("GET","report_data.xml",true);
	xmlhttp.open("GET","sensitive_data.xml",false);
	xmlhttp.open("POST","saveData",true,"myUserName","somePassord");


b) setRequestHeader(name, value)

Upon successful initialization of a request, the setRequestHeader method of the XMLHttpRequest object can be invoked to send HTTP headers with the request.

Example:

	//Tells server that this call is made for ajax purposes.
	xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');  


c) send(payload)

To send an HTTP request, the send method of the XMLHttpRequest must be invoked. This method accepts a single parameter containing the content to be sent with the request.
The content is necessary in POST requests. For GET methods, imply pass null as parameter.

Example:

	xmlhttp.send(null); //Request with no data in request body; Mostly used in GET requests.
	xmlhttp.send( {"id":"23423"} ); //Request with data in request body; Mostly used in POST/ PUT requests.


4) abort()

This method 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.

Syntax:

	//Abort the processing
	xmlhttp.abort();

Apart from above method, onreadystatechange event listener is very important which we will discuss in next section.

Synchronous and Asynchronous requests

XMLHttpRequest object is capable of sending synchronous and asynchronous requests, as required within webpage. The behavior is controlled by third parameter of open method. This parameter is set to true for an asynchronous requests, and false for synchronous requests.

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

The default value of this parameter is “true” if it is not provided.

Asynchronous Ajax Requests do not block the webpage and user can continue to interact with other elements on the page, while the request is processed on server. You should always use asynchronous Ajax Requests because a synchronous Ajax Request makes the UI (browser) unresponsive. It means 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 Request should be used if you’re embedding a new JavaScript file on the client using ajax and then referencing types and/or objects from that JavaScript file. Then the fetching of this new JS file should be included through using a synchronous Ajax Request.

Example synchronous request

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
}

Example asynchronous request

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)


In above example, onreadystatechange is a event listener registered with XMLHttpRequest request. onreadystatechange stores a function that will process the response returned from the server. It 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 will be changed and set to some other value. Lets have a look at possible values:

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

Handling returned response from server

To get the response from a 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

Example code:

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

Demo application code

For demonstration purpose, I am creating a very simple hello world application. In this application, webpage sends a ajax GET request to query the current server’s system time. In response, server sends the current time. Easy enough.

ajax demo application


Asynchronous request example

To enable the webpage to send such 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, a 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);
	}
}

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

ajax demo application success


Synchronous request example

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 response will be available only when request is completed. Till the time, page will be blocked.

Some popular ajax capable libraries

As it is evident that ajax is very popular technology nowadays for making webpages highly interactive and user friendly. To ease the development of ajax related components, various frameworks are available for developers in market today. The good thing is that they all are free to use.


1) JQuery

JQuery is probably the post 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 else where
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');
      }   
  }); 
});


2) 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 now. I will write more posts on ajax in future. You may like to register your email id for update notifications.

Source code download

Happy Learning !!

Ads by Google

42 thoughts on “Complete AJAX tutorial”

  1. Hello Lokesh,
    I have a problem in developing code for Gridview using AJAX with JavaScript.
    So, give me some sample code for reference. How to develop gridviews using AJAX with JavaScript.

      1. Hi sir, can u explain how to work flow?

        $.ajax({
        	type: 			'POST',
        	contentType: 	'application/json',
        	url: 			rootURL,
        	dataType: 		"json",
        	data: 			formToJSON(),
        	success: 		function(data, textStatus, jqXHR){
        						alert('Wine created successfully');
        						$('#btnDelete').show();
        						$('#wineId').val(data.id);
        					},
        	error: 			function(jqXHR, textStatus, errorThrown){
        						alert('addWine error: ' + textStatus);
        					}
        });
        

        }

        1. In short, jQuery API will create a browser native XMLHttpRequest object and set the parameters passed as options [type,contentType,url,dataType,data]. Then it will send the request to server. Upon getting the response back, either it will call success or error function. More details are already given in above tutorial.
          And if you really want to go deeper for seeking any specific fact; the read the official documentation http://api.jquery.com/jquery.ajax/.

  2. how to create calender option to choose any particular date in java language and to how to store it in database ?

  3. hello sir,
    i have a requirement like if user click on like link count increase without refresh the page.
    i did it though passing argument to javascript fuction like
    function likecomment(arg){

    document.location = ‘/LikeComment?id=’+arg;
    }
    i want to make like link as ajax then that without refreshing the page i want to like the comment.

    1. I wrote some pseudo code for you. Make it working in your application.

      function likeCommentRequest(requestURL)
      {
          //Creating a new XMLHttpRequest object
          var xmlhttp;
          if (window.XMLHttpRequest){
              xmlhttp = new XMLHttpRequest(); 
          } else {
              xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
          }
          //Change if you want to POST the data
          xmlhttp.open("GET", reqURL, true);
           
          xmlhttp.onreadystatechange = function() {
              if (xmlhttp.readyState == 4) {
                  if (xmlhttp.status == 200)
                  {
                      //Increase the like count here in html
                  }
                  else
                  {
                      //Show some error
                  }
              }
          };
          xmlhttp.send(null);
      }
      
    1. 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

      onreadystatechange: Stores a function (or the name of a function) to be called automatically each time the readyState property changes

  4. I have a Registration page.. I need to pass the input values to servlet using ajax and json..
    And also i need to retrieve it in servlet…

    1. I can help you here if you already have attempted something and struck anywhere. Starting from scratch is not possible for me due to my busy schedule.

  5. Hey, I’m learning AJAX . I know a little bit of Java, HTML,CSS and JavaScript. I tried to implement your example & I couldn’t. I’m posting my code here. Please tell me where I’m going wrong.

    The HTML Page : get-current-time,html is the file name.

    Hello World in Ajax!

    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);
    }

    Message from Server::

    The Servlet is : GetTimeServlet.java

    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.PrintWriter;
    import java.util.Date;

    /**
    * Servlet implementation class GetTimeServlet
    */
    public class GetTimeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
    * @see HttpServlet#HttpServlet()
    */
    public GetTimeServlet() {
    super();
    // TODO Auto-generated constructor stub
    }

    /**
    * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    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);
    }

    /**
    * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    }

    }

    Please help me out. if possible.

    1. Really I can not provide much help with this much information. I would like to know what is the problem you are facing. What’s environment in which app is running. OR, please zip your project sourcecode and send me at howtodoinjava[at]gmail[dot]com.

    2. You didn’t put url. Create a page name like india.jsp and give it into that url it will work

  6. please can u explain different advantages and disadvantages with the prototype ajax call and jquery ajax call? And which parameter should help to decide which model will be more convenient to use at certain place?

  7. Though not a developer, tutorial is excellent – and removed the great confusion.
    Till now, I didn’t understand and afraid of the word – AJAX.
    Thanks

  8. Hi Lokesh
    I am implementing an module to access unique id of an remote url, I am using iframe to load remote url eg http://www.thirdpartyurl.com I need to access unique id from this page element. for eg image or any element which is in third party url.

    I did it using javascript and jquery and it is working fine for local page eg. d:testpageproduct.html but its not working for remoter url for eg http://www.shopping.com. I am unable to access the unique id.

    I’m getting two kind of errors.
    1. Uncaught SecurityError: Blocked a frame with origin “null” from accessing a frame with origin “null”. Protocols, domains, and ports must match. (only in GOOGLE CHROME for both local and remote page)
    2. [18:52:10.608] Error: Permission denied to access property ‘nodeType’ @ http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js:4 (FIREFOX)

    So now i am planning to resolve this two issues by using java.

    I kindly request you to provide tips and resources. It will be a great help for me and my time will be saved. I am a fresher in java.

    Looking forward your helps.

    Thanks
    Ganesh

  9. I want to learn many things from you please tell me your fees or atleast if i am able to get your notes on Spring,AJAX,Hibernate,Maven,RESTful

    Please reply as i want to update myself.

    1. My humble advice: “please have patience”. Next thing, I do not teach for money and reason is I do not have time for this. Sorry if it disappoints you. Based on my very “busy” career of 7 years, I can advice you that nothing pays more than hard work. And let me tell you golden rule : “LEARN ANYTHING NEW ***EVERYDAY***”.

      1. Nice advice Mr. Lokesh. .
        Your site really helps to all because, compare to other tutorial sites, we can learn only the theory, but here you have provided sample and it can be downloaded . . so really nice . . :)

        if you can post about Spring,Struts and Hibernate, i will feel more happy and sure i know that you will . . i’m waiting . .

    1. Tough question. I have not really used netscape in my entire life. As much I know, nobody does it today as there is whole range of modern browsers which are just more than awesome.

Note:- In comment box, please put your code inside [java] ... [/java] OR [xml] ... [/xml] tags otherwise it may not appear as intended.

Leave a Reply

Your email address will not be published. Required fields are marked *


− three = 5

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>