JQuery is a very popular java script library. We can implement AJAX technique using JQuery’s built in AJAX API.

In previous post, we learned how to use java script AJAX with Servlet application. In this article, we will learn how to use JQuery AJAX API. We are using Eclipse IDE for this example.

Following are the steps to implement JQuery AJAX

  • Create a Dynamic web project, a HTML page and import JQuery js library.
  • Add JQuery AJAX script to access the servlet class.
  • Create a Servlet class to handle the AJAX request.

Create a Dynamic web project, a HTML page and import JQuery js library

Since we are using JQuery for AJAX calls, we have to create a Dynamic web project, called “AjaxExample”, create a HTML page inside WebContent folder and import JQuery java script file on our html page. Add the following code to HTML page header to import JQuery js file.

< script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

We can also download the js file and put it anywhere inside Webcontent folder and link it inside our html page(index.html).

Add JQuery AJAX script to access the servlet class

Since we have imported JQuery js file in our previous step, now we can call JQuery AJAX API in our java script function. Create an input text field and a button, add an on click event to the button and call a java script function and add required JQuery AJAX code. Following is the complete index.html file after adding all the required code.

index.html

<!DOCTYPE html>
< html>
< head>
< meta charset="ISO-8859-1">
<title>Insert title here</title>
< script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" ></script>
</head>
< body>
< h2>JQuery AJAX Example</h2>
Enter your name:
< input type="text" id="name"/><br/>
< button onclick="callJqueryAjax()">Submit</button>
< br/>< br/>
< h3 id="result"></h3>

function callJqueryAjax(){
var name = $('#name').val();
$.ajax({
url     : 'AjaxHandler',
method     : 'POST',
data     : {name : name},
success    : function(resultText){
$('#result').html(resultText);
},
error : function(jqXHR, exception){
console.log('Error occured!!');
}
});
}
</body>
</html>

In the above code, we have an input text box, with name attribute “name” where user can enter any text and submit it by clicking the button. We have bounded on click event of this button to java script function called “callJqueryAjax()”. Inside function callJqueryAjax() we are getting the value entered by the user on text field, and sending it to servlet calledAjaxHandler’ through AJAX POST method.

Once the response is successfully received from Servlet, we are printing the response text to <h3> html component. In case of error, error is logged on browser console.

Few of the useful JQuery Ajax function attributes are given below:

  • url : URL of the Servlet/ resource to be invoked.
  • method : HTTP method type like GET, POST, etc.
  • success : call back function on successful completion of AJAX call.
  • error : call back function in case of any error occurs during AJAX call.
  • data : Request data to be sent while POSTing the request.
  • beforeSend : Pre- request callback function. returning false from this function will cancel the request.
  • complete : Callback function, executed after finishing the request(with success or error).
  • contentType : Request content type like: application/x-www-form-urlencoded, multipart/form-data, or text/plain, etc.
  • headers : Request headers.
  • timeout : Set a timeout for the request. Values in milliseconds.

Create a Servlet class to handle the AJAX request

Final step is to create a servlet class, which can handle the AJAX request sent from browser. Create a class called AjaxHandler.java and add the follwoing code.

AjaxHandler.java

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 {
  doPost(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String name = request.getParameter("name");
  response.getWriter().print("Hello "+ name + "!!");
}
}

In the above code, we are implementing doPost() method and inside doPost() method, we are retrieving the “name” request parameter and sending back response to browser along with appended greeting text “Hello”.

Now our JQuery Ajax example is complete. Run the application and following page should appear on hitting the http://localhost:8080/AjaxExample home page.

Jquery Ajax

After submitting the AJAX request, results are shown as below.

Jquery Ajax example

You may also interested in: