Jquery AJAX example with Servlet

JQuery is a very popular javascript library. We can implement the AJAX technique using JQuery’s built-in AJAX API.

In the previous post, we learned how to use javascript AJAX with the Servlet application.

In this article, we will learn how to use JQuery AJAX API. We are using Eclipse IDE for this example.

Create the Jquery Ajax servlet application

Since we are using JQuery for AJAX calls, we have to create a Dynamic Web project, called “AjaxExample”, create an HTML page inside the WebContent folder, and import the JQuery javascript file on our html page. Add the following code to the HTML page header to import the 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 to our html page(index.html).

Add JQuery AJAX script to access the servlet class

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

<!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 the name attribute “name” where the user can enter any text and submit it by clicking the button. We have bounded on click event of this button to javascript function called callJqueryAjax(). Inside the function callJqueryAjax() we are retrieving the value entered by the user on the text field.

We are also sending it to a servlet called AjaxHandler through the AJAX POST method.

Once the response is successfully received from Servlet, we are printing the response text to <h3> html component.

In case of an error, we are logging the error message on the browser console.

The below are a few of the useful JQuery Ajax function attributes:

  • 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 request

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

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 the doPost() method and inside the doPost() method, we are retrieving the “name” request parameter and sending back a response to the browser along with appended greeting text “Hello”.

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

Jquery Ajax

After submitting the AJAX request, we get the results as shown below.

Jquery Ajax example

Conclusion

In this article, we learned how to use JQuery AJAX API using the Eclipse IDE.