Ajax(Asynchronous Java script And XML) is a technique used in web development for creating a faster updates to user interface and better user experience. Ajax makes use of the XMLHttpRequest object to communicate with servers. Using ajax, data can be posted to back end server without page submit or reloading the browser page.

In this post, we will learn how to use Ajax technique to invoke back end servlet, get the response from servlet and modify the user interface accordingly. We will learn simple java script ajax example.

Following are the steps to create our Ajax application with Servlet:

Create a java dynamic web application

In this example, we are using Servlet for back end, which handles the requests made through Ajax call and sends JSON response back to the browser. Create a dynamic web project on Eclipse IDE. We are creating a dynamic web project called “AjaxExample” as shown below.

ajax_project

Create a servlet class

In previous step we created the dynamic web project. Now Create a servlet class under src folder. Let’s call it AjaxHandler.class. This Servlet class handles the Ajax call from our front end html page. In this class, we are using hard coded JSON object values as response. Servlet class returns a JSON array back as response upon invoking through Ajax call.

Note that to create JSON objects, we need to add dependency jar to the class path or lib of our dynamic web project. In this example, we have used org.json jar. Download the latest jar and add it on class path or put it under WEB-INF/ lib directory.

In the code below, We have implemented HTTP GET method. We are creating a JSON array and adding two JSON objects to the array and finally returning this JSON array  back to through response. Our JSON object contains name” and “age attributes. Also note that the response MIME type is set to “application/json“, as we are returning JSON data.

AjaxHandler.class

import java.io.IOException;

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

import org.json.JSONArray;
import org.json.JSONObject;

@WebServlet("/AjaxHandler")
public class AjaxHandler extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public AjaxHandler() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        JSONArray array = new JSONArray();
        
        JSONObject user1 = new JSONObject();
        user1.put("name", "TOM");
        user1.put("age", "26");
        JSONObject user2 = new JSONObject();
        user2.put("name", "ASB");
        user2.put("age", "26");
        
        array.put(user1);
        array.put(user2);
        
        response.setContentType("application/json");
        response.getWriter().write(array.toString());
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

Invoke the servlet using Ajax from html page

In previous step, we created our back end servlet. Now final step is to create a html page and add Ajax call into it. Create a html page index.html under Webcontent folder of our dynamic web project. Add the follwoing html content to the page. Here, we are calling back end servlet using http GET method(using XMLHttpRequest) and upending the content returned from servlet on the div html element with id “contentDiv”.

<!DOCTYPE html>
< html>
< head>
< style>
#contentTable, th, td{
border : solid 1px black;
}
< /style>
< /head>
< body>
< h2>Ajax Example with Servlet</h2>

< button onclick="callAjax();">Get Data</button>
< br/>< br/>


< table id="contentTable">
< tr>
< th>Name</th>< th>Age</th>
</tr> 
< /table>
< div id="loading"></div>

< script type="text/javascript">
function callAjax() {

document.getElementById('loading').innerHTML = "Loading Data...";

httpRequest = new XMLHttpRequest();

if (!httpRequest) {
console.log('Unable to create XMLHTTP instance');
return false;
}
httpRequest.open('GET', 'AjaxHandler');
httpRequest.responseType = 'json';
httpRequest.send();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {

document.getElementById('loading').innerHTML = "";

if (httpRequest.status === 200) {

var array = httpRequest.response;
for (var i=0; i< array.length; i++) {

var table = document.getElementById('contentTable');
var row = table.insertRow(table.rows.length);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var name = document.createTextNode(array[i].name);
var age = document.createTextNode(array[i].age);
cell1.appendChild(name);
cell2.appendChild(age);
}
} else {
console.log('Something went wrong..!!');
}
}
}
}
</ script>
</ body>
</ html>

Brief Explanation:

We have used httpRequest.open(), which opens HTTP connection for us. First parameter(“GET” in our case) tells which HTTP request method to be used. Then we pass URL of the server with second parameter.

We can also pass a third optional parameter (with value: true or false), which notifies that whether our request is Asynchronous or not. Default value of this parameter is “true”.

Nest we have used httpRequest.send() method, which send our request to server. We can also send any data by passing parameter to this method, when we are using POST request. The data should be in the format, which can be handled by the server. If we are POSTing the data, then we may have to set the request header with requests content-type as shown in the example below:

httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

AJAX responds with ready state value as XMLHttpRequest.DONE (or value corresponding to 4), which means complete response has been received from the server.The list of ready state values are:

  • 0 – Indicates request is not initialized.
  • 1 – Server connection is established (or loading).
  • 2 – request is received (or loaded).
  • 3 – request is processing (or interactive).
  • 4 – request is completed and response has been received (or complete ).

Once the response is ready, we are checking the HTTP response status code, which is 200 OK if the response has been properly received.

The response sent from the server is retrieved with httpRequest.response, which contains the response data. Also note that we have set the response type as “json“, since we are sending the response in JSON format from our Servlet.

We can also retrieve response by using :

  •  httpRequest.responseText – Returns response in the form of String or text.
  • httpRequest.responseXML – Returns response in the form of XMLDocument.

Finally, It’s time to run the application.

We are using Apache Tomcat to run the application. Following is the page before making the AJAX call to the server.

 

ajax_output1

After receiving the response back to browser.

ajax_output2

Also Read:

Versions Details:

  • Eclipse Helios
  • Apache Tomcat v8.
  • json-20140107.jar