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

There seems to be an issue with Ajax functionality within the WordPress admin

As a beginner level WordPress developer, I am currently halfway through creating a newsletter plugin administration panel. Unfortunately, the jQuery.post ajax I am using for form submission in this admin panel is not working. Strangely enough, the same Wor ...

Angular directive for resizing C3 charts

I've recently implemented a basic donut chart using C3, which I've enclosed in a directive and everything is functioning smoothly. Below is the code for my directive: angular.module('dashboardApp').directive('donutChart', fu ...

Encountering Issues with Accessing Property

Upon trying to run my code, the console is displaying an error that I am unable to resolve. The error specifically states: "TypeError: Cannot read property 'author' of undefined." View the StackBlitz project here The error seems to be coming fr ...

Issue encountered while attempting to adjust a date (the modification was incorrect)

I am currently working on developing a calendar feature using Angular. Part of this project involves implementing drag and drop functionality to allow users to move appointments from one day to another. However, I have encountered a strange issue. When at ...

Invoke the cs function with the data in the JavaScript code by utilizing AJAX

After the user clicks on the Delete button, I am trying to access a cs function from a js function on an aspx page and send the ID to the cs function. Below are the codes I have tried: JS function deleteClick(ID) { '<%Session["ID"] = "&ap ...

Stop users from signing up if the chosen username is already in use

I have a script that successfully checks if a username is available, but even if the username is already taken, the user can still register. I am looking for a way to prevent registration if the username is not free. Here is the code snippet: index.php $ ...

ObjectArray in Node.js

Building an object array in my node app involves transforming another object array. Let's assume the initial object array is structured like this... levels: [ { country_id: 356, country_name: "aaa", level0: "bbbb", level1: "cccc", level2: "dddd", le ...

How can I turn off the animation for a q-select (quasar select input)?

I'm just starting out with Quasar and I'm looking to keep the animation/class change of a q-select (Quasar input select) disabled. Essentially, I want the text to remain static like in this image: https://i.stack.imgur.com/d5O5s.png, instead of c ...

Is there a radio button that can dynamically update and modify the current view?

Although I don't consider my issue to be overly complex, as a newcomer I am struggling to find a straightforward solution. The form I have collects various items and on the output page generates a table based on this data. For instance, one question ...

Is there a way to transform a time string, for instance "8:02 AM", into a sortable field?

I am currently working with a MongoDB database that stores times as strings, and I want to filter queries based on specific time ranges. For instance, the time fields in my database are formatted as "8:02 AM" and "10:20 PM", and I am looking to refine my ...

The function $.ajax({}) is not recognized in the Django framework

I have been searching for a solution to this specific problem, but none of the related questions I found were able to help. There must be another reason why it's not working, but I'm finding it difficult to pinpoint the issue. Here is the code sn ...

Utilizing React and Google Code to Enhance Lead Conversion Pages

I have developed a basic react application featuring a contact form. Upon submission, I aim to display the Google Code for the lead Conversion Page within the application. <!-- Google Code for Purchase Conversion Page --> <script type="text ...

Using node.js to download files with axios, streaming the content, and then

I am attempting to download a PDF file using axios, and save it on the server side using fs.writeFile. My code is as follows: axios.get('https://xxx/my.pdf', {responseType: 'blob'}).then(response => { fs.writeFile('/temp/my ...

Ensuring Code Execution Order in NODE.JS

I've encountered an issue with my code that involves parsing a pcap file, storing the data in an array data = [], and then writing it to a JSON file: var fs = require("fs"); var pcapp = require('pcap-parser'); var hex = ""; var data = []; v ...

The useCallback hooks persist outdated values when the list is refreshed

Why am I not getting the expected values every time the function onRefresh is called using Hooks? Example when onRefresh is called twice: Expected values: true 0 20 false true 0 20 false Received values: false 0 0 false false 20 20 false Initial st ...

Click to Rotate the Shape

I am attempting to apply a rotation effect on a shape when clicked using jQuery and CSS. My goal is to select the element with the id of x and toggle the class rotate on and off. The rotate class utilizes the CSS transform property to achieve the desired r ...

Refreshing the page when the button is clicked to upload files using AJAX

I have created a form and I need to send a file along with some other information via Ajax to a PHP file. The issue I am facing is that when I attempt to upload the file, the page refreshes after clicking on submit. How can I prevent this page refresh? Ad ...

Painting Magic: Exploring the World of Canvas Zoom and Moves

I'm having trouble implementing zoom and pan functionality for this particular canvas drawing. While there are examples available for images, my case is different since I am not working with images. Any tips or suggestions on which libraries to use wo ...

Effectively monitoring coordinates on both the client and server sides

I'm currently in the process of developing a multiplayer game using websockets, node, and JavaScript. I need advice on the most effective approach to update client information and manage their coordinates on the server. The method I am using at the mo ...

Updating an element's HTML content from a template URL using AngularJS

Can someone help me figure out how to set the html of an element in my directive based on a dynamic template url? element.html('some url to a template html file'); rather than using element.html('<div>test</div>').show() ...