How to call Servlet from Ajax jQuery - onlyxcodes

Thursday, 13 May 2021

How to call Servlet from Ajax jQuery

Hi, in this tutorial you will learn how to call servlet from Ajax jQuery. In any web application, asynchronous JavaScript and XML (AJAX) is commonly used. It's the process of communicating data with a live server and upgrading portions of a website without having to relaunch the whole page. 


I'll show you how to use JQuery to make AJAX calls from a JSP page to a Servlet and then view the response from the Servlet on the same JSP page. 


To put it another way, this article will teach you how to use AJAX in Java web applications. Rather than implementing it in Javascript, I'm using the JQuery library because it's slow to make it operate for all browsers in Javascript, and JQuery eases it into a single program.


How to call Servlet from Ajax jQuery

I'm assuming you already have Eclipse IDE installed on your system. 


Create A New Project

Step 1 – Launch the Eclipse IDE. As seen in the illustration, go to File -> New -> Dynamic Web Project.


go to File -> New -> Dynamic Web Project.

Step 2 – In the second stage, I only typed the project name below, and I placed the other default configuration unchanged. After you've filled in your name, click the Next button. 


Project Name – call servlet from ajax


typed the project name

Step 3 – A new window has opened. I used the default configuration, and now we'll build a Servlet class in the src folder. 


used the default configuration

Step 4 –   Finally, the final step in establishing a project. Choose the Finish button. Since it isn't needed, I unchecked the checkbox for generating web.xml file deployment descriptor. 


final step in establishing a project.

See the complete project directory structure, as well as the additional packages we'll create in this project, ahead. 


Note:  I've already saved the jQuery file in the JS folder and imported the bootstrap package folder into the WebContent folder for a better user interface. 


project directory structure - How to call Servlet from Ajax jQuery

index.jsp

Inside the WebContent folder, construct a JSP page with the name index. Build a simple form with an input text box and a submit button using the bootstrap classes on this page.


This JSP page's input text box request is sent to the Servlet using an ajax method. 


<form id="formID" class="form-horizontal">
				
	<div class="form-group first_division">
	<label class="col-sm-3 control-label">Enter Name</label>
	<div class="col-sm-6">
	<input type="text" id="txt_name" class="form-control" placeholder="enter name" />
	</div>
	</div>
				
	<div class="form-group first_division">
	<div class="col-sm-offset-3 col-sm-6 m-t-15">
	<input type="button" id="btn_submit" class="btn btn-success btn-block" value="Submit">
	</div>
	</div>
			
	<b><h2 class="text-success text-center" id="show_result"></h2></b>
					
</form>

See how to send a POST request from ajax to a servlet and get a response from the servlet on the same JSP page without reloading. 


How to call Servlet from Ajax jQuery - JSP using JavaScript - how to get response from servlet using ajax - jQuery- JSON example - how to send POST request from ajax to servlet

jQuery / Ajax Code

In the index.jsp page that was recently developed, the jQuery and Ajax code begins before the closing </html> tag. 


When the user clicks the send submit button, the click() method triggers and executes the event button. The #btn_submit id attribute of the button.


#txt_name is the id attribute of the name text box using that attribute the .val() method to get the text or name value.


If the user types a name in the text box and clicks the submit button, the $.ajax() function triggers and sends the text box value request to the servlet “FetchAjaxRequest” using HTTP POST.


The ajax function also responsible to get a response from a servlet, We display the response text to the <h2> HTML section tag once the Servlet response is successfully obtained.


Using the JavaScript reset() method to erase all the values of the form elements, the #formID is the id attribute of the form tag.


<script src="js/jquery-1.12.4-jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function(){
       $('#btn_submit').click(function(){
    	   
        var name=$('#txt_name').val();
         
        if(name=="")
       	{
			alert("Please enter your name ! ")	 
        }
        else
        {
            $.ajax({
               url:'FetchAjaxRequest',
               type:'POST',
               data:'yourname='+name,
               success:function(response)
               {
                   $('#show_result').html(response);
                   $('#formID')[0].reset();
               }
            });
        }
         
		}); 
    });
</script>

jQuery Ajax function attributes guides :


url: The URL to which the request is sent is included in this string. 


The URL "FetchAjaxRequest" is the Java Servlet class file to be invoked in this example.


type:  POST, PUT, and GET are instances of HTTP requests. GET is the default. 


We submit the value of the text box in this example using a POST request. 


data: This is the data that will be sent to the server. It can be a JSON object, a string, or an array of JSON objects. 


In this example, ‘yourname' is a string that saves and submits the value of the text box. 


success: When an Ajax request succeeds, a callback function is called. 


This function was used to load the Get response from Servlet response within the <h2> tag of an HTML element in this example.


Other attributes,


dataType: The type of data you get from the server, such as text and JSON example.


error: If the request fails, this callback function is called. 


complete:  When the request is completed, this callback function is called. 


contentType: When sending MIME content to the server, a string containing a content type. "application/x-www-form-urlencoded, text/plain, etc charset=UTF-8" is the default.


cache: Browser cache is indicated by a boolean. True is the default value.


To process the AJAX request, create a Servlet class. 


FetchAjaxRequest.java

The last move is to build a servlet class that can receive AJAX requests from the browser. Add the following code to a class named FetchAjaxRequest.java. 

package com.onlyxcodes;

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;


@WebServlet("/FetchAjaxRequest")
public class FetchAjaxRequest extends HttpServlet {
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		String name = request.getParameter("yourname");
		response.getWriter().print("Hi, "+ name);
	}
}

Explanation:


In front of the class, the @WebServlet annotation specifies the servlet URL. When the user submits the form, the servlet container calls the servlet's doPost method. Within the doPost method, we will complete the following tasks.


The getParameter() method is used to get user-defined text box values which are transferred through the ajax data property.


A request is an object of HttpServletRequest and the response is an object of HttpServletResponse. These objects are used to get requests from browsers and to send responses to users. 


Using the response object, we are sending a response to the browser with the welcoming text "Hi" attached. 


The getWriter() method delivers word text to the user, and we publish the output on the browser JSP page as a response using the print() method.



Download Codes

No comments:

Post a Comment