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

Why does JSON.parse obscure objects in response body when using Node.js?

Whenever I utilize JSON.parse and output some fetched information with the require module, nested objects are shown as [Object]. For example, consider the following code (currently using Node version 10.15): const request = require("request"); const ur ...

Prevent mobile users from entering text with Material UI Autocomplete on keyboard

Currently, I am utilizing the Material UI Autocomplete component for multi-select functionality. Although it functions perfectly on desktop, I want to prevent keyboard input on mobile devices and only allow touch selection. Essentially, I do not want the v ...

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 ...

Reduce JSON for efficient deserialization and persistence of intricate POJOs using JPA/Hibernate

Dealing with deserialization of a complex POJO from a JSON string and persisting it in a MySQL database can be quite challenging. Below is a simplified example class: @Entity @Table(name="a") public class A{ private Long id; private B b; priva ...

Automatically numbering text boxes upon pressing the enter key

Is there a way to automatically number textboxes when I type "1" and hit enter in one of them? For example, if I have 3 textboxes and I type "1" in the first one, can the other textboxes be numbered as 2 and 3 accordingly? <input type="text&qu ...

What is the process for creating files from an array of bytes, zipping those files, and transferring the zip to the server on Android without storing the files locally?

I am looking for a way to send a zip file to the server without creating it in Android storage. The task involves making files from an array of bytes, archiving them in a zip format, and then sending it to the server. Any suggestions on how to achieve thi ...

jquery's animation causing elements to move abruptly when containing text

For the past hour, I've been grappling with jQuery and could really use some assistance. The following example showcases smooth animations: when you click on either of the divs, the selected div will move left or right if the viewport is wider than 70 ...

Combining Framer Motion with Next.js: Resolving conflicts between layoutId and initial props in page transitions

As I work on creating smooth image page transitions using Framer Motion and Next.js with layoutId, I've come across a challenge. Here is my main objective: The home page displays an overview with 3 images When an image is clicked, the other images f ...

@PostMapping add a null value to the database

I am currently working on a REST application and encountering issues when using @PostMapping. I have two classes with models - TblEmployees and TblDepartments, which are connected via a foreign key named "dbID". When I try to insert the following data: { ...

Having difficulty with a script not functioning properly within an onclick button

In my script, I am using the following code: for (var i in $scope.hulls) { if ($scope.hulls[i].id == 1234) { console.log($scope.hulls[i]); $scope.selectedHullShip1 = $scope.hulls[i]; } } The code works fine outside of the onclick button, but fails to run ...

Fetching dynamic information via AJAX for a jQuery tooltip

I have successfully loaded content via AJAX, including a UL element with li items that each have tooltips. Now I want to load tooltip content via AJAX for each individual li item. How can I achieve this? Currently, I am making an AJAX call to load the li ...

Grasping the idea of elevating state in React

I can't figure out why the setPostList([...postList, post]) is not working as expected in my code. My attempts to lift the state up have failed. What could be causing this issue? The postList array doesn't seem to be updating properly. I'v ...

show a function written in JavaScript

I’m currently developing an API and looking to demonstrate a JavaScript code example for invoking this API. While writing a test function in JavaScript, I aim to execute and showcase the code for the JavaScript functions. However, my preference is to ha ...

Exploring the chosen choice in the Material Design Lite select box

Consider the following scenario. If I want to extract the name of the country chosen using JavaScript, how can this be achieved? <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label getmdl-select getmdl-select__fullwidth"> ...

What is the best way to isolate the text before a particular segment within a string, excluding any blank spaces?

Is it possible to use vanilla JavaScript in order to extract the first string value directly to the left of a specified portion of a longer string, excluding any blank spaces? Consider the following string: 1 hr 30 min How could you extract the 1 located ...

The AJAX email submission form is not functioning properly

Recently, I have upgraded my email sign-up form on the website to include validation. However, after adding the validation, the form no longer sends and an error message is not displayed. Upon inspecting, I found the following error: TypeError: null is ...

Optimal approach for verifying the POST request payload

My RESTful API has a POST endpoint for user creation, and I am looking to implement data validation before inserting it into the database. There are two approaches I'm considering: Approach 1: Incorporating model validation in the controller and repe ...

What are the steps to setting up SystemJS with Auth0?

I am having trouble configuring SystemJS for Auth0 (angular2-jwt) and Angular 2.0.0-beta.6 as I keep encountering the following error message: GET http://localhost:3000/angular2/http 404 (Not Found)fetchTextFromURL @ system.src.js:1068(anonymous function) ...

What is the best way to loop through an API response in Vue.js?

Hey there, I'm new to Vue and struggling with iterating through data in my template. Despite being able to log everything properly, I can't seem to render it on the page. Here's the API URL: https://private-922d75-recruitmenttechnicaltest.a ...

Ways to initiate a transition upon clicking a button, causing it to switch from being hidden (`display: none`) to visible (`display: block`)

I'm attempting to create a smooth transition effect when a button is clicked, similar to a toggle function, where the content below it seamlessly shifts instead of abruptly moving. The classic example of this is the Bootstrap navbar hamburger menu, wh ...