localization password policy ajax call feature deep

How to do a Simple Ajax Call to a Servlet using JQuery

Today we are going to learn how to make a simple Ajax calls using jquery to a servlet. For those who do not know what an ajax is, let me give a brief idea. An ajax call is something which is the dream of every developer/coder. Why? Because you get the chance to make calls to a server in order to request/receive or send data without submitting your form. Moreover, you also get to update your webpage without even reloading it. Doesn't it sound pretty amazing? Oh yes I know you might be wondering how much complex it might be. So did I but trust me its way easy that you can ever think of.
The Ajax call logic that I will show you works 100% on all major browsers like Firefox, Internet Explorer, Chrome. So simply follow the process below.

First of all, let us create a new dynamic web project. I am using eclipse IDE. Of course, you can use any IDE you want but please be informed that certain steps for creation of project/classes/pages might vary. Okay, let's first click on File->New->Dynamic Web project. Give a project name and click on finish.

Next, we would create a folder structure as shown below:


folder structure

As you can see from the above picture that our project name is Practice.
Next right click on JSP_Pages and click on New->Jsp file. Provide the name of the page you want. I have given the name as Ajax.jsp-> click on finish.

Now we will build a simple login form using some HTML tags and bootstrap classes.

Ajax call code


<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<title>my ajax</title>
<form class="form-horizontal" role="form" action="#" autocomplete="off" method="post">&nbsp;
<div class="col-lg-9"><input id="username" class="form-control" required="" type="text" placeholder="Username" /></div>
<div class="form-group">

<div class="col-sm-offset-3 col-sm-9"><button class="btn btn-success btn-sm" type="button">Sign in</button></div>

<script type="text/javascript">
function valUser() {
if (null == $('#username').val() || $('#username').val() == '') {
alert("enter username");
return false;
} else {
var name = $('#username').val();
var dataString = "username=" + name;
type : "POST",
url : "/Practice/GetUser",
data : dataString,
dataType : "text",
success : function(data) {
// alert("success data :"+data);
var ajaxResponse = $("#ajaxResponse").html(data)
//If we get any error from the server
error : function(jqXHR, textStatus, errorThrown) {
console.log("Something really bad happened "
+ textStatus + ";" + errorThrown);



At first, create an input field in order to enter a username, a button, and an output field to display the final output. Remember to set the "type" attribute of the button to button. Since we do not want to submit the form else our purpose for doing Ajax will get defeated.

A brief explanation follows for the ajax code under the script tag. Inside the valUser() we are checking if the username value is null or empty. If this case is true we would generate an alert. Else we would proceed with the ajax call. The username value is stored in the name variable. Moreover, the URL attribute contains the context path followed by the name of the servlet, where we want to receive the sent username. In the dataString, we are trying to set and send the username to the servlet for in order to send/request any data from the server. The success function is the one where we should get the response if every other thing works well else we get the error in the error function.

Servlet code


import java.io.IOException;
import java.io.PrintWriter;

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

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

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);

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

String username = request.getParameter("username");

String greetings = null;
if (username.equalsIgnoreCase("admin")) {
greetings = "admin";
} else {
greetings = "welcome";
response.setContentType("text/html; charset=UTF-8");

} catch (Exception e) {
// TODO: handle exception


The output:

jquery output
Great, now let us go through the servlet. Over here we are receiving the username from the Ajax call using the getParameter() method of request object. We are performing a simple logic here, simply checking if the username is equal to admin or something else and accordingly we populate the value of a string named "greetings". Post this we simply write it to our response object.

Again we come back to the jsp page where we did the ajax call. We should get a response in the success function. And the response is in the data parameter of success function like success: function(data). Furthermore, we can show the response to the user by binding it with an id. In our case, we bind the result with the ajaxResponse id of the output tag. The response can also be collected in a var like I did in var ajaxResponse to perform any other logic.

Finally, you can view the output in your browser. That's it we are done!!

If you liked this post please share and comment. And don't forget to check our other posts.

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.