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 !!

Was this post helpful?

Join 8000+ Awesome Developers, Like YOU!

56 thoughts on “AJAX Tutorial”

  1. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.

    Reply
  2. Hi, Is it possible to call a java class in ajax url parameter directly, without creating a servlet or struts action?

    $.ajax({
    url: "com.mypackage.MyClazz",
    ...
    })
    
    Reply
  3. hey thanks for this great article about ajax.Its really helpful as java beginner to know about ajax . Here i have found a brief intro of AJAX and how it is important in java. Thanks for sharing this.

    Reply
  4. i want to fetch city dropdown vakues according to the state dropdown values…i am working on spring and hibernate framework and mysql database now …
    pls help me sir

    Reply
  5. I am trying to use like clause in preparedstatement bu i am getting error
    code snippet:—

    private static final String SEARCH_EMP_DEATAILS_BASED_ON_FIRST_NAME="SELECT FIRSTNAME, LASTNAME, CITY,STATE,ADDRESS,PHONENO,EMAIL,ROLE,EMP_CODE FROM EMP_REGISTER WHERE FIRSTNAME LIKE ?";
    
    con=ConnectionUtility.getConnection();
    	ps=con.prepareStatement(SEARCH_EMP_DEATAILS_BASED_ON_FIRST_NAME);
    	ps.setString(1,pattern+'%');
    	rs=ps.executeQuery();
    

    error:— java.sql.SQLException: Fail to convert to internal representation

    Reply
      • SELECT FIRSTNAME, LASTNAME, CITY,STATE,ADDRESS,PHONENO,EMAIL,ROLE,EMP_CODE FROM EMP_REGISTER WHERE FIRSTNAME LIKE ‘ra%’;

        Yes i tried this query in db and it is executing but in my program it is getting error, please give solution

        Reply
  6. I want to use ajax, jquery and json in my application.
    my aim:-In my jsp page when i enter ‘first name’ then it should be displayed all the possible matching names from the database and display the fetched data in a tabular format in same jsp page page. Either using spring 4.x or struts 1.x

    Please give me solution for this, i want to implement it as soon as possible

    Reply
  7. Thank you for a great work! I’ve check you code. It will works only if I change ajaxAsyncRequest("get-current-time") to the ajaxAsyncRequest("/MyApp/index.jsp"), ajaxAsyncRequest("") or if I give name “get-current-time” to my project.

    Reply
  8. 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.

    Reply
  9. 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.

    Reply
    • 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(&quot;Microsoft.XMLHTTP&quot;); 
          }
          //Change if you want to POST the data
          xmlhttp.open(&quot;GET&quot;, 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);
      }
      
      Reply
    • 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

      Reply
  10. 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…

    Reply
  11. 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.

    Reply
    • 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.

      Reply
  12. 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?

    Reply
  13. 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

    Reply
  14. 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’ @ (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

    Reply
  15. 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.

    Reply
    • 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***”.

      Reply
      • 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 . .

        Reply

Leave a Comment

About HowToDoInJava

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

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