Creating an AJAX data form in a JSP scenario

I want to correctly set up the data parameter for the ajax call.

<script type="text/javascript">
    $(document).ready(function() {
        $('#call').click(function ()
        {
            $.ajax({
                type: "post",
                url: "books", //this is my servlet
                data: <<< my data here >>>
            });
        });

    });
</script>

This snippet is from my jsp:

<form action="books" method="post">
    <table width="70%" border="1">
        <%
            List<Book> books = (List<Book>) request.getAttribute("books");

            for (int i = 0; i < books.size(); i++) {
        %>
        <tr>

            <td>
                <input type="checkbox" name="book<%=i%>"
                       value="<%= books.get(i).getBook_id()%>"> <%= books.get(i).getName() %>
            </td>

        </tr>
        <%
            }
        %>
    </table>

    <select name="user_name">
        <%
            List<User> users = (List<User>) request.getAttribute("users");
            for (int i = 0; i < users.size(); i++) {
        %>
        <option value="<%=users.get(i).getName()%>"><%=users.get(i).getName()%></option>
        <%
            }
        %>
    </select>
    <input type="submit" name="submit" value="Purchase">
    <input type="button" value="Call Servlet" name="Call Servlet" id="call"/>
</form>

I aim to transfer all the data that usually goes through the form above. Can you guide me on how to use the ajax technology in this scenario?

Answer №1

Assign a unique instance id to the form and utilize it with the serialize() method

       $('#form').submit(function ()
        {
            $.ajax({
                type: "post",
                url: "books", //servlet for handling the form data
                data: $(this).serialize()
            });
        });


    <form id="form" action="books" method="post">
        <table width="70%" border="1">
            <%
                List<Book> books = (List<Book>) request.getAttribute("books");

                for (int i = 0; i < books.size(); i++) {
            %>
            <tr>

                <td>
                    <input type="checkbox" name="book<%=i%>"
                           value="<%= books.get(i).getBook_id()%>"> <%= books.get(i).getName() %>
                </td>

            </tr>
            <%
                }
            %>
        </table>

        <select name="user_name">
            <%
                List<User> users = (List<User>) request.getAttribute("users");
                for (int i = 0; i < users.size(); i++) {
            %>
            <option value="<%=users.get(i).getName()%>"><%=users.get(i).getName()%></option>
            <%
                }
            %>
        </select>
        <input type="submit" name="submit" value="Purchase">
        <input type="button" value="Call Servlet" name="Call Servlet" id="call"/>
    </form>

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

Refresh the Server Component once data has been modified by the Client Component within Next.js

I am still grappling with this specific scenario and trying to figure out the best approach in Next.js 13. Can anyone provide guidance on the correct way to handle this? In a Server Component, I have a list of users being displayed, leveraging MongoDB, as ...

Interactive data table feature in React, transferring selected row data to a modal pop-up

I am currently developing an offline Progressive Web App (PWA) using ReactJS and have integrated the react-data-table-component, which has been very helpful so far. Within the table, I have implemented an onRowClicked function that triggers whenever a row ...

exploring methods to prevent flash of unstyled content (fouc)

Looking for a way to control CSS with a cookie: Want the user's style choice to stick until they change it or the cookie expires Avoid any default styling issues when the user returns Avoid using jquery, libraries, or frameworks Need compatibility w ...

The duration required to render DOM elements

Trying to determine the best method for measuring the rendering time of DOM elements in a web browser. Any tips? I'm currently developing an application that involves significant DOM manipulation as part of comparing the performance between Angular 1 ...

What are the different ways to upload files with multiple file input options?

Is there a way to upload multiple files using separate file input types or do I need to use just one input type and CTRL+click the files? My back end is written in perl. <form action="dsadsa" method="post" enctype="multipart"> <tr> ...

Error: Attempted the use of 'append' method on an object lacking the implementation of FormData interface, with both processData and contentType set to false

Apologies for any English errors. I am attempting to use ajax to submit a form, and here is my JavaScript code: $("#formPublicidad").on('submit', function(event) { event.preventDefault(); var dataForm = new FormData(document.getElementBy ...

Guide on replacing buttons with <a> tags in express.js posts

I've incorporated handlebars as my chosen templating engine and I'm utilizing buttons to trigger app.post() in my JavaScript file. <form method="POST" action="/smo_assessment"> <div class="container" id="div1"> <h3 id="header" ...

Tool that closely mirrors the functionalities of Google Maps

Seeking to develop an interactive image feature on my website akin to Google Maps but with custom images. Desiring functionalities like drag, scroll, and zoom in/out for enhanced user experience. Interested in any suggested tools or plugins for this purp ...

Load additional slides in bxslider, monitor when it has reached the last one

I am using a horizontal carousel slider with bxslider, and I have disabled the infiniteLoop feature to prevent the slider from looping. My goal is to fetch additional slides via an AJAX request and add them to the slider once it reaches the end of the cu ...

React SVG not displaying on page

I am facing an issue with displaying an SVG in my React application. Below is the code snippet: <svg className="svg-arrow"> <use xlinkHref="#svg-arrow" /> </svg> //styling .user-quickview .svg-arrow { fill: #fff; position: ...

Protractor is unable to locate the password input field on Gmail using its ID

Currently, I am in the process of configuring Protractor to test my application. However, I am encountering a roadblock as it requires authentication through Gmail and I am struggling with the login process: describe('Vivace Home page', function ...

Is there a way to retrieve the file path of the file that is imported using an alias in Vite (Vue3)?

Hello! I have a few inquiries. Is it feasible to obtain the file path of the file utilizing an alias for import in Vite (Vue3)? Setup Here's the directory structure I'm using, purely for illustrative purposes: src/ module_a/ some_ ...

A step-by-step guide on uploading files from the frontend and saving them to a local directory using the fs and express modules

I'm considering using fs, but I'm not entirely sure how to go about it. Here's the setup: ejs: <form action="/products" method="POST"> <input type="file" name="image" id="image"> <button class="submit">Submit</but ...

Finding the location of PIE.htc in the Firebug tool

After encountering issues with CSS3 properties not working on IE 7 and IE 8, I decided to include PIE.HTC. Visit this link for more information Upon viewing the page in IE, I realized that the CSS3 properties were not being applied as expected. I attempt ...

Unable to resize react-split-pane dimensions

I recently integrated the react-split-pane plugin into my project, but I am encountering some issues with its functionality. Even though I have tested react-split-pane versions 0.1.68, 0.1.66, and 0.1.64, none of them seem to work as expected in my applic ...

I am looking to pair a unique audio clip with each picture in my collection

I have implemented a random slideshow feature that cycles through numerous images. I am now looking to incorporate a brief audio clip with each image, synchronized with the array I have established for the random pictures. The code snippet below is a simil ...

Understanding how types intersect in TypeScript

I'm currently diving into Type Relations in TypeScript. Can someone help explain what happens when we intersect the types represented by these two expressions: {a:number}[] & {b:string}[] Does this result in {a:number, b:string}[] ? Any clarificat ...

In strict mode, duplicate data properties are not allowed in object literals when using grunt-connect-proxy

I recently started following a tutorial on AngularJS titled "Hands on Angularjs" by Tutsplus. In the tutorial, the instructor uses the grunt-connect-proxy package to redirect ajax requests to a Rails server running on localhost:3000. However, I believe the ...

AngularJS fetches the 'compiled HTML'

If I have this angularjs DOM structure <div ng-init="isRed = true" ng-class="{'red': isRed == true, 'black': isRed == false}"> ... content </div> How can I obtain the 'compiled' version of this on a cl ...

Is there a way to retrieve the selected value from a dropdown menu using vue.js?

I have a parent Vue component structured like this: <template> <form> <div class="row"> <div class="col-md-4"> <form-select id="color" name="color" :data="color">Color</form-select&g ...