Sending data from an AJAX request to a Spring controller is a common task in web

var TableDatatablesEditable = function () {

    var handleTable = function () {

        function restoreRow(oTable, nRow) {
            var aData = oTable.fnGetData(nRow);
            var jqTds = $('>td', nRow);

            for (var i = 0, iLen = jqTds.length; i < iLen; i++) {
                oTable.fnUpdate(aData[i], nRow, i, false);
            }

            oTable.fnDraw();
        }

        function editRow(oTable, nRow) {
            var aData = oTable.fnGetData(nRow);
            var jqTds = $('>td', nRow);
            for (var i = 0; i < jqTds.length; i++) {
              jqTds[i].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[i] + '">';
            }
            jqTds[7].innerHTML = '<a class="edit" href="">Save</a>';
            jqTds[8].innerHTML = '<a class="cancel" href="">Cancel</a>';
            oTable.fnDraw();
        }

        function saveRow(oTable, nRow) {
            var jqInputs = $('input', nRow);
            for (var i = 0; i < jqInputs.length-1; i++) {
               oTable.fnUpdate(jqInputs[i].value, nRow, i, false);
            }
            oTable.fnUpdate('<a class="edit" href="">Edit</a>', nRow, 7, false);
            oTable.fnDraw();

            var form_data = {
                // your data objects here
            };
            
            // AJAX call to save data

        }

        function cancelEditRow(oTable, nRow) {
           var jqInputs = $('input',nRow);  
           for(var i=0;i<jqInputs.length-1;i++){ 
             oTable.fnUpdate(jqInputs[i].value,nRow,i,false); 
           } 
           oTable.fnUpdate('<a class="edit" href="">Edit</a>', nRow, 7, false);
           oTable.fnDraw(); 
        
        }

        var table = $('#sample_editable_1');
        var oTable = table.dataTable({ // Your datatable initialization settings });

        var tableWrapper = $("#sample_editable_1_wrapper");
        var nEditing = null;
        var nNew = false;

        $('#sample_editable_1_new').click(function (e) {
            e.preventDefault();
            // Add new row logic
        });

        table.on('click', '.delete', function (e) {
            e.preventDefault();
            // Delete row logic
        });

        table.on('click', '.cancel', function (e) {
            e.preventDefault();
            // Cancel edit row logic
        });

        table.on('click', '.edit', function (e) {
            e.preventDefault();
            // Edit row logic
        });
    }

    return {

        //main function to initiate the module
        init: function () {
            handleTable();
        }

    };

}();

jQuery(document).ready(function() {
    TableDatatablesEditable.init();
});

This is the JavaScript code snippet which includes functions to edit, save, and cancel rows in a DataTable.

The ajax part of the code sends the edited data from the table to a Spring MVC controller. The controller method receives the data and saves it using DataTemplatesave class.

@RequestMapping(value = "/save1", method = RequestMethod.GET)
public ModelAndView dataTemplateedit(HttpServletRequest req) {
    // Extract data from request parameters
    // Create ListDataDefinition object and save data using DataTemplatesave
    return new ModelAndView("save1");
}

This is the Spring MVC Java code that handles the saving of edited table data.

Answer №1

From my understanding, there is no need to use request.getParameter for every parameter if you already have a bean with the corresponding property name.

You can simplify it by directly using the following code:

@RequestMapping(value = "/save1", method = RequestMethod.GET)
public ModelAndView dataTemplateedit(ListDataDefinition ldd) {
    DataTemplatesave.save(ldd);
}

It seems like you are autowiring DataTemplatesave. As a suggestion, consider maintaining camel case for better code readability and maintenance.

@Autowired
private DataTemplatesave dataTemplatesave;

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 display the form values on the table once it has been submitted?

I'm struggling with my form input not showing up under the table headings after submission. I've reviewed the code multiple times, but can't figure out what's causing the issue. If you have any suggestions on how to write the code more ...

Display additional inputs using the PHP Foreach Loop depending on the selection made

I have a PHP Foreach loop that includes a "Quantity" input field. When users select a quantity, the corresponding number of new inputs should be displayed. For example, if the user chooses a quantity of "3", then 3 new inputs should appear for that item. K ...

I recently designed a form using a combination of HTML and JavaScript in order to display different dialogues depending on the number of selections made. Unfortunately, the alert function does not seem to be functioning

The concept is to have users select options and then receive employment sector suggestions based on their selections. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF ...

Showing particular URL text upon opening a new window using JavaScript

I've encountered an intriguing scenario. In my application, there's a feature that triggers a new window/tab to open when a button is clicked. Upon opening, a predefined HTML page is shown to the user with a specific URL set. I'm curious abo ...

A guide on retrieving query string parameters from a URL

Ways to retrieve query string parameters from a URL Example Input - www.digital.com/?element=fire&solution=water Example Output - element = fire solution = water ...

Adjust the initial scroll position to - apply overflow-x: scroll - on the specified element

I have an image that can be scrolled to the right on screens that do not fit the full width, but I want the center of the image to be displayed first instead of the left side. Below is my React code: import React, { useEffect, useRef, useState } from &qu ...

Every time I try to loop through my JSON object using an $.each statement, an error is thrown

When I execute an $.each loop on my json object, I encounter an error 'Uncaught TypeError: Cannot read property 'length' of undefined'. It seems that the issue lies within the $.each loop as commenting it out results in the console.log ...

Add the child's input query first and then concentrate on it

I have successfully appended a div with a child input, but I am facing an issue where the newly appended input is not getting focused when added. $(document).ready(function() { var max_fields = 10; //maximum input boxes allowed var wrapper ...

Analyzing JSON information using an AJAX request from a local file

I have a PHP file on a web server that is executing queries to a MySQL database. Currently, I am testing a site on my local PC which utilizes a JS file with AJAX requests to retrieve JSON data from the mentioned PHP file. My question is whether it is fea ...

What is the process for creating a transparent default color theme in MUI?

I'm looking to make an element's background color the primary main color with some transparency using Material-UI. I've attempted a couple of methods, but unfortunately neither have worked for me. Any suggestions or guidance would be greatly ...

Click on the navigation bar buttons to toggle between different divs and display multiple information boxes simultaneously

Here is the current code snippet... $("#contact").click(function() { if ( $( "#contact_div" ).length ) { $("#contact_div").remove(); } else { var html='<div id="contact_div" class="contact-info"><p>Contact info</p&g ...

How can I implement an AJAX request with MongoDB in Node/Express?

Let's begin with a simple webpage: an HTML Form, a button, and a div-box. When the button is clicked, the Form data will be sent via AJAX. The data will then be stored in MongoDB and retrieved into the div-box seamlessly without any page refresh. A ...

How to prevent the parent element from scrolling when changing the value of a number input by scrolling

Within a container with fixed dimensions and scroll bars that appear when the content size exceeds the container, there is a form. This form contains an input of type "number" which allows changing its value using the mouse wheel. The issue arises when at ...

What is the best way to retrieve the current font size of a link element?

Is there a way to determine the font size of an element in pixels or points? Are there alternative methods available to achieve this? I am looking to increase the size of <a href="...">MAKE ME BIGGER</a> by 130%, 140%, N% based on its current ...

Drop draggable items on top of each other

I'm wondering if there's a way to drag jQuery elements into each other. To illustrate my question, I've duplicated this code (link) and made some style changes. Here is the updated version: Fiddle Link. In the current setup, you can drag e ...

What is the significance of the A tag when parsing a URL?

So, I encountered a problem that involved parsing a URL to extract the hostname and pathname, then comparing the extracted pathname with a string. If you need help with this issue, check out this post: How do I parse a URL into hostname and path in javasc ...

Guide on adding markers using Google Maps API based on specific criteria

Hi there, I need assistance in developing the following requirements. In my database, there is parking lot information. Let's say each parking lot has two attributes: id and address. Via a spring controller, I am passing a list of parking lots t ...

Identify user input with Python Selenium for keyboard and mouse interactions

As a frequent user of Selenium Browser for my everyday browsing needs, I am looking to implement some code that will be triggered when certain keys are pressed on any page. Initially, I considered loading JavaScript onto each page to track key and mouse in ...

The session name has not been properly defined

Sorry for any errors in translation. I'm facing an issue where the session name I insert is coming up as undefined. However, when I manually enter the username, everything works fine. View Image <? php session_start (); echo var_dump ($ _SESSION ...

Obtain the text that is shown for an input field

My website is currently utilizing Angular Material, which is causing the text format in my type='time' input field to change. I am looking for a way to verify this text, but none of the methods I have tried give me the actual displayed text. I a ...