Making Ajax requests to a servlet from a JSP form and dynamically updating a <div> element with the response

As I navigate my way through learning about ajax, I am currently exploring how to execute an ajax call from a JSP form and then showcase the result in a designated div. The following JSP form effectively loads data into divOrderResultContainer; however, I am seeking guidance on achieving the same outcome using an ajax call instead of having to refresh the page each time.

The Index.jsp file:

<html>
<head>
<link rel="stylesheet" type="text/css" href="css/view.css" media="all">
<script type="text/javascript" src="JavaScript/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="JavaScript/Calender.js"></script>
</head>
<body>
</div>
<hr>
<div id = "divuserinputContainer">
<table align="center" id="table">
<form name="orderform" action="OrderController" onsubmit="return validateForm()" method="POST"">         
<td class="label">Branch Number
<select name="branch" >
<option selected value="0">All Branches</option><option selected value="1">100</option>                                                   
</select>
</td>
<td class="label">Service Type
<select class="SelectionBoxes" id="Serviceselect" name="Serviceselect" >
<option selected value="A">All</option>
<option value="D">Delivery</option>
</select>
</td>
<td class="label" >Order Status
<select class="SelectionBoxes" id="Orderstatus" name="Orderstatus">
<option selected value="O">All</option>
<option value="P">Placed</option>
</select>
</td>
<td>
<button class="submit" name="submit" id="submit">Submit</button></td>
</form>
</tbody>
</table>
</div>
<hr>
<div id="divOrderResultContainer">
<table id="ViewOrderResultContainer" border=1>
<thead><tr><th>OrderNumber</th>
<th>ServiceType</th>
<th>OrderStatus</th>
</tr></thead><tbody><c:forEach items="${orders}" var="order"><tr>
<td><c:out value="${order.ordernumber}" /></td>
<td><c:out value="${order.slotservice}" /></td>
 <td><c:out value="${order.orderstatus}" /></td>
</tr></c:forEach></tbody></table>
</div>
</body>
</html>

The OrderController.java servlet:

@WebServlet(name="OrderServlet",urlPatterns={"/OrderController"})
public class OrderController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public OrderController() {
        super();

    }   
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        Int branchNumber = request.getParameter("branch");      
        String serviceType = request.getParameter("Serviceselect");     

        OrderDao dao = new OrderDao();
        try {           
            request.setAttribute("orders",dao.getallorders(branchNumber,serviceType));              
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        RequestDispatcher view = request.getRequestDispatcher("Index.jsp");
        view.forward(request, response);        
    }

    }

I would appreciate any insights on how to implement an ajax call from a JSP form after the user clicks the submit button, or if you could direct me to some useful examples. Thanks in advance!!!

Answer №1

For the purpose of ajax request and response, utilize the following:

 $(document).ready(function () {
                $('#pinServId1').click(function () {
                    var value= $("inputField Id").val();
                    var request = $.ajax({
                        url: "/servletUrl",
                        method: "POST",
                        dataType: "text",
                        data: {userPassword: value}
                    });
                    request.done(function (response) {
                        $('#IdofDivtoDisplayOutput').val(response);
                    });
                    request.fail(function (jqXHR, textStatus) {
                    });});
                });

When working within a servlet,

        OutputStream outStream = response.getOutputStream()) {
        response.setContentType("text/xml");
        outStream.write(stringVariableName.toString().getBytes());//change name
        outStream.flush();

This code will generate the desired string output for ajax response. Insert this in the doPost method of the servlet.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to leverage JavaScript to click on one div and modify the settings of another div simultaneously?

I am struggling with my code which has unnecessary information. <div> <div id="one" class="button"></div> <div id="two" class="button"></div> </div> <div> <div class="Home tab"> < ...

Steps for removing the bottom border for the last child in the Material UI Box Component

I have a Box Component where ListItems are wrapped. For each child, I have a border-bottom of 1px solid class set for the Box component, but I don't want it for the last child. How can I achieve that? {data.map((item, i) => { return ...

The process of enzyme shallow rendering involves the rendering of child components

Currently, I am attempting to shallow render a component in order to conduct some elementary unit tests. This particular component contains two child components that are rendered multiple times based on the parent's props. Upon querying the shallowl ...

Removing a Cookie in a Servlet

I developed an application with a login filter that involves creating a cookie as shown below. Cookie ck = new Cookie("testCookie","Value"); ck.setPath("/"); response.addCookie(ck); For the logout process, I am removing the cookie like this. Cookie ck = ...

web browser editing tool

Do you know which library was utilized to create this JSON editor? https://i.sstatic.net/kGpGz.png You can find it at . The editor efficiently checks the syntax and shows errors when necessary. ...

Combining the powers of Express.js, Sequelize, and advanced form validation

As a beginner with Express and Sequelize, I am looking to utilize Sequelize's validation functionality for form submissions without having to duplicate validations on the frontend or rely on additional libraries like express-validator. Below is an exa ...

Inquiry regarding the ng-disabled directive in AngularJS

<div ng-app="myApp" ng-controller="myCtrl"> <button type="submit" class="btn btn-primary pull-left" ng- disabled="captchaError">Submit</button> </div> <script> var app = angular.module('myApp', []); app.controller( ...

Execute the function using the method

Why am I unable to call the getCar () method of my Car function? In class, the teacher assigns the app variable to the express() function like this: const app = express(), and then he calls the app.get methods from the app. Why am I having trouble callin ...

Retrieve the elements with the largest attributes using the find method exclusively

UPDATE: After some trial and error, it seems like using the find method won't work for this particular scenario. I managed to come up with a workaround by introducing a boolean field called "last_inserted" and utilizing Meteor hooks to ensure that onl ...

Supervising the organization of HTML sections for an offline web application

Currently, I am developing an offline HTML5 application that involves a significant amount of DOM manipulation through the creation of HTML strings within JavaScript functions. For example: var html=''; html+='<div class="main">&apos ...

Identify the appearance of a web component being added to the Document Object

After reading this discussion regarding a web-component I created: <my-vue-web-comp [userId]="1" id="my-component"></my-vue-web-comp> The component functions properly in Angular. How can I determine when the web component h ...

The Correct Approach for Implementing Error Handling in a Node.js API Server

In my Node.js API server, I encountered an issue with error handling. To tackle this problem, I developed a module specifically for error handling. When in development mode, this module sends JSON objects containing errors to the API client. Here is an exa ...

Having trouble scanning the directory /db/migration in Spring Boot (native mode) due to an unsupported protocol: resource

My current setup includes: Spring boot 3.1.2 and flyway-core:9.21.0 running in native image mode. Upon application startup, I am encountering the following message: Unable to scan location: /db/migration (unsupported protocol: resource) originating from ...

Navigating Unknown Properties in Angular: A Guide to Iterating Through Arrays

I'm having trouble coming up with a title for my question. I want to loop through an array of dynamic objects coming from a database, but I don't know the properties of the objects. Here's an example of the array object: [{ "id": 9, ...

Using AJAX and JQUERY to display a value in HTML

JavaScript <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#but").click(function(){ $.ajax({ ...

jQuery plugin is not effectively targeting the directive

Recently, I have been experimenting with using a sleek jQuery datepicker and decided to turn it into a directive for my angular app. The implementation of the directive is currently very straightforward: directive('datePicker', function() { ...

The MobX computed function is triggered before the item is fully added to the array

I am currently using React in combination with MobX. In my store, I have an observable array called 'conversations' and I want to create a sorted version of this array as a computed property. However, when I add a new conversation, the sortedConv ...

What methods can I use to evaluate the efficiency of my website?

Is there a way to assess and improve website performance in terms of load time, render time, and overall efficiency? I've heard of YSLOW for firebug, but am curious if there are any other tools or websites available for this purpose. ...

"Figuring out a way to include a link with each image in a react-s

I am currently working on a project in Gatsby and encountering some issues with the homepage banner. I am using react-slick which seems to be functioning fine, but when I try to add content on top of each image, it causes some problems. Specifically, setti ...

The chat text will automatically scroll down, displaying information loaded from the database

Is there a way to ensure that chat text always remains scrolled to the bottom of the chat? I have tried multiple tutorials and examples from Stack Overflow, but none seem to work for me. Currently, my chat text overflows the textarea when there are too m ...