Guide on using Ajax and spring MVC to dynamically fill a modal form

One JSP page displays database results in a table on the browser, allowing users to edit or delete each row. I want to implement a feature where clicking the edit link fetches specific customer data from the database using Spring MVC and Hibernate, displaying it in an edit modal for editing purposes.

Below is a code snippet with the line

  • Edit Customer Detail
  • serving as the link to edit the customer information. I'm unsure whether to use an AJAX function, and if so, what that function would look like, and how it will call the modal.

    I found this solution (Spring MVC Populate Modal Form), but it lacks details on calling the modal to populate values from AJAX. Are there alternative methods available? Any guidance would be appreciated. Thanks!

    <c:forEach var="customer" items="${customers}" varStatus="status">
        <tr>
            <td><c:out value="${status.count}" /></td>
            <td><a title="Go to the Company Certificate Detail">${customer.customerName}</a></td>
            <td>${customer.contactName}</td>
            <td>${customer.street}</td>
            <td>${customer.state}</td>
            <td>${customer.zipCode}</td>
            <td>${customer.country}</td>
            <td>${customer.email}</td>
    
            <!-- More content -->
    
            <td>
                <div class="btn-group">
                    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                        Actions <span class="caret"></span>
                    </button>
                    <ul class="dropdown-menu" role="menu">
                        <li><a data-toggle="modal" data-target="#editCustomerModal">Edit Customer Detail</a></li>
                        <li><a data-toggle="modal" data-target="#deleteCustomerModal_${customer.id}" >Delete Customer</a></li>
                    </ul>
                </div>
            </td>
        </tr>
    
        <div id="deleteCustomerModal_${customer.id}" class="modal fade">
            <!-- Delete Customer Modal Content -->
        </div>
    </c:forEach>

    Edit Modal:

    <div id="editCustomerModal" class="modal fade" role="dialog">
        <!-- Edit Customer Modal Content -->
    </div>

    Answer №1

    Here's a helpful tip: add a hidden value for the customer ID in your edit model.

    <input type="hidden" id="customerIdInput" path="customerId" class="form-control" />
    

    Instead of a submit button, change it to a regular button for saving the customer details.

    <div class="modal-footer">
        <div>
            <button type="button" class="btn btn-default updateCustomer" data-dismiss="modal">Save</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
    </div>
    

    For more flexibility, consider modifying the JavaScript code particularly in the AJAX section.

    <script type="text/javascript">
    
        function ajaxCall(customerId) {
            $.ajax({
                type: "POST",
                url: "/clause/getUpdate?customerId="+customerId ,
                success: function(result) {
                    //update the customer list page
                }
              }
        });
    
        $('.updateCustomer').on('click', '.accountsEmployees', function () {
            customerId = $("#customerIdInput").val();
            ajaxCall(customerId);
    
        }
    </script>
    

    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

    Troubleshooting: Wordpress plugin experiencing issues with jquery loading functionality

    Currently, I am in the process of developing a WordPress plugin and encountering an issue with loading information on keyup for one of the pages. Despite my efforts, I am unable to locate the file no matter what steps I take. The specific folder name for t ...

    Only displaying sub items upon clicking the parent item in VueJS

    I'm in the process of designing a navigation sidebar with main items and corresponding sub-items. I want the sub-item to be visible only when its parent item is clicked, and when a sub-item is clicked, I aim for it to stand out with a different color. ...

    Changing color of entire SVG image: a step-by-step guide

    Check out this SVG image I found: https://jsfiddle.net/hey0qvgk/3/ <?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 19.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <svg version="1.1" width="90" height="9 ...

    Using both jQuery and Ajax can result in multiple requests being sent when utilizing the focus

    Hey there, I've got a form with around 20 input fields. My goal is to trigger an AJAX request every time a user moves from one field to another. Everything seems to be working fine, but there's a peculiar issue. Upon moving from one field to th ...

    Creating dynamic captions in an Angular grid is an essential feature for enhancing the

    Is there a way in Angular to dynamically update the grid titles based on an array of elements in the model? How can I display them as captions? For instance, imagine we are currently in week 202010. I would like to automatically generate the next five wee ...

    I encountered an SyntaxError while working with Ionic. The error message reads: "Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>)."

    Here's the code that is causing me trouble: this.http.get('http://localhost/....) .map((res) => res.json()) .subscribe(( this.navCtrl.push(OtpPage,{mobileno:this.mobile}); }, (err) => { console.log(err ...

    Django and VueJS: Error 403 - Forbidden request due to missing or incorrect CSRF token

    My tech stack includes Django and Django REST framework on the backend, along with Vue.js on the frontend. While GET requests function smoothly and POST requests using Postman or Insomnia work fine, encountering an error in the Browser console when sending ...

    Warning: React has detected that a non-boolean value of `true` was received for the attribute `my-optional-property`

    source code import React from "react"; import { Button, ButtonProps } from "@material-ui/core"; interface MyButtonProps extends ButtonProps { "aria-label": string; "my-optional-property"?: boolean; } function MyCustomButton(props: MyButtonProps) { ...

    Guide to automatically update mysql posts every second

    Utilizing ajax, I am able to save user posts/comments into a mysql table without the need for a page refresh. Initially, there is this <div id="posts-container"></div> Next, I attempted to use Jquery load() to iterate through a table and disp ...

    CKeditor does not accept special characters or diacritics in keywords

    Recently, I came across a helpful code snippet for CKeditor that counts and ranks the most used words in a textarea. This feature is invaluable for generating SEO-keywords suggestions while writing articles. However, there is an issue with non-English char ...

    Having issues with NextJs app router and redux-toolkit not resetting to initial state after server-side rendering (SSR)

    I am facing a challenge in my NextJs project with the app router and redux/toolkit for state management. When navigating from one page to another, the data fetched on the previous page remains in the redux state even though it wasn't fetched on the cu ...

    How come the data in the datatable does not appear sorted as it was retrieved from the ajax response?

    I am successfully able to load the Datatable using ajax. However, I am facing an issue where the table does not display the data in the same order as it is received. The data is fetched from report_ajax.php [json] {"data":[ ["22:00:00" ...

    Combining arrays of objects in JavaScript

    I am currently working on combining different arrays: const info1 = {id: 1} const info2 = {id: 2} const info3 = {id: 3} const array1 = [info1, info2] const array2 = [info1, info3] const array3 = [info2, info3] const union = [...new Set([...array1, ...arr ...

    Google Bar Graphs Cannot Display Decimal Values

    Having an issue with my bar chart from Google Chart not displaying float numbers. Other types of bar charts provided by Google Chart work fine, but this specific type doesn't show the float numbers. Here is the code I have written: http://jsfiddle.ne ...

    Customize the CloseIconButton in Material-UI Autocomplete for a unique touch

    Hello everyone, I have a simple dilemma. I am trying to implement a custom closeIconButton, but the only available prop is closeIcon. However, this prop is not sufficient because I need this custom button to also have an onClick property. If I add the onC ...

    Modify a specific field in a row of the table and save the updated value in a MySQL database

    I have successfully retrieved data from a database and displayed it in a table. Now, my goal is to enable editing of a specific field within a row and save the updated value back into MySQL. Here is the code snippet that includes displaying the data in th ...

    What is the most elegant way to retrieve a new item from Firebase and read it?

    My goal is to display the result of a successful read on a page, with only one attempt available before the headers are set and the page is sent. I am looking to retrieve one new value, generated after a listener was initiated so as not to pull existing da ...

    Issue with if statement when checking element.checked

    Hey everyone, I'm currently working on a calculator app and running into an issue. I have set up 3 radio buttons and I would like to check them using an 'if statement' in my JS file. However, the problem is that the 'main' element ...

    The operation could not be completed with exit code 1: executing next build on Netlify platform

    Having trouble deploying my Next.JS site to Netlify due to a build error. The site was working fine previously. Any suggestions on how to resolve this issue? 3:43:14 PM: - info Generating static pages (2/6) 3:43:14 PM: - info Generating static pages (4/6) ...

    How to choose the option in one select box based on the selection in another, and vice versa

    How can I dynamically select options in one select box based on the selection of another, and vice versa? I am using Ajax to redirect to a query page. while($result = mysql_fetch_assoc($query1)) { echo "<option value=".$result['username' ...