Sending real-time form field information to a spring rest controller via ajax

I am currently working on sending dynamic form data to a spring controller through AJAX in order to save a list of objects to the database later. Although everything seems to be properly configured, I am encountering difficulties in dealing with dynamic form data within the AJAX process. Specifically, the challenge lies in creating JavaScript objects for each row of a table and then posting these objects as JSON data.

HTML

 <html>  
  <head>  
       <title>Add Students</title>  
       <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
       <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
  </head>
<body>  
       <div class="container">  
            <div class="form-group">  
                  <form id="student_detail" name="student_detail">

                        <table class="table table-bordered" id="student_dynamic_table">
                            <tr>
                                <td><input type="text" name="name[]" id="name" placeholder="Enter Name" class="form-control name_list" /></td>
                                <td><input type="text" name="age[]" id="age" placeholder="Enter Age" class="form-control age_list" /></td>
                                <td><button type="button" name="add" id="add" class="btn btn-success">+</button></td>
                            <tr>
                        </table>
                        <input type="button" class="btn btn-info"  id="submit" name="submit" value="Submit" />
                  </form>
            </div>  
       </div>  
  </body> </html>

JS

$(document).ready(function(){  
  var i=0;  
  $('#add').click(function(){  
       i++;  
       $('#student_dynamic_table').append('<tr id="row'+i+'"> <td><input type="text" name="name[]" id="name'+i+'"  placeholder="Enter Name" class="form-control name_list" /></td><td><input type="text" name="age[]" id="age'+i+'"  placeholder="Enter Age" class="form-control age_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">x</button></td><tr>');  
  });
  $(document).on('click','.btn_remove', function(){

  var button_id=$(this).attr("id");
  //id of the clicked button
  $('#row'+button_id+'').remove();
  });
$('#submit').click(function(){            
      var url= "${pageContext.request.contextPath}";

       var  student = ({
            name : $('#name').val(),
            age : $('#age').val()
        });  

$.ajax({
        type : "POST",
        url : url + '/submitDynamicForm',
        data:JSON.stringify(  student),
        dataType : 'json',
        contentType : 'application/json',
        success : function(response) 
        {
        }
   });  }); });  

Controller

@Autowired
private StudentDao studentDao;

@RequestMapping(value = "/dynamic", method = RequestMethod.GET)
public ModelAndView getDynamicForm() {
    ModelAndView form = new ModelAndView("dynamicform");
    return form;
}

@RequestMapping(value = "/submitDynamicForm", method = RequestMethod.POST)
public void saveUser(@RequestBody List<Student> student) {

    studentDao.insertListOfStudents(student);
  } }

Model

@Entity
public class Student {

@Id
@GeneratedValue
private Long id;

@Column(name = "name")
private String name;

@Column(name = "age")
private int age;

// getters setters

 }

Hibernate code to insert list of students

@Transactional
public void insertListOfStudents(List<Student> student) {
    Session session = sessionFactory.getCurrentSession();
    for(Student std : student) {
        session.save(std);
    }

Your assistance is greatly appreciated

Answer №1

let totalRows = $('#student_dynamic_table tr').length; // retrieve the total number of rows
let studentData = {}; // create an empty object to store student data
for (let i = 0; i < totalRows; i++) { 
    studentData[$("#row"+i).val()] = $("#age"+i).val();  // assign values to keys in the studentData object
}

data: { "jsonData": JSON.stringify(studentData) },  // submit the formatted data through AJAX

// In your controller, access the data using .key() and .value(), remember to parse it with JSON.parse first.

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 retrieve the central anchor point position (x, y) of the user's selection in relation to the document or window?

Is there a way to retrieve the center anchor point position (x, y) of the user's selection relative to the document or window? I have tried using window.getSelection() to get selected nodes, but I am unsure how to obtain their position: See an examp ...

Deciphering a JSON reply with the Unmarshal function

Currently, I am attempting to parse a JSON response using the code provided below: type Token struct { access_token string `json:access_token` token_type string `json:token_type` expires_in int `json:expires_in` } homeURL := "https:/blah.com/ ...

Why is the JSON conversion expecting a String instead of an Object when a List is used in the code?

Trying to convert my JSON data into POJO, but encountering an error when sending a post request. The error message received is: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 1 ...

executing a hook within _app.tsx in Next.js

The issue I'm facing involves the rendering of a hook that helps determine if my components are within the screen's view to trigger animations. This hook is executed in _app.tsx, however, it doesn't run when switching to another page. Oddly ...

Designing websites using elements that float to the right in a responsive manner

Responsive design often uses percentage width and absolute positioning to adjust to different screen sizes on various devices. What if we explore the use of the float right CSS style, which is not as commonly used but offers high cross-browser compatibilit ...

Transmitting information from the front-end Fetch to the back-end server

In my stack, I am using Nodejs, Express, MySQL, body-parser, and EJS. My goal is to trigger a PUT request that will update the counter by 1 when a button is pressed. The idea is to pass the ID of the clicked button to increment it by 1. app.put("/too ...

"Error: The ajax call to the dojo endpoint is not retrieving the

Uncertain where I might have made a mistake as the code appears correct to me. I have confirmed that file.php -> mod_rewtite -> file.json is functioning properly by testing the JSON response through jQuery. However, the following code snippet immedia ...

Angular Material (8) error code S2591: The variable 'require' is not defined in the current scope

Currently, I am attempting to record the date and time in the JavaScript console. Despite the code successfully logging the dates, an error message persists: Note: The code is functioning properly, with the dates being displayed in the console. It is only ...

displaying a collection of images from a designated tag on a flickr gallery

Hello, I need some help with my flickr gallery. I want to load only the first two pictures from a specific tag defined in a 'data-category' attribute into a div named 'gallery'. Here is my HTML: <div data-category="clouds ...

What is the process of using JavaScript code to read a text file?

Trying to use Google Charts while reading data from a text file. The code in JS is written for this purpose: function readTextFile(file){ var rawFile = new XMLHttpRequest(); rawFile.open("GET", file, false); // using synchronous call var allTe ...

Utilize JSON and Python to streamline data filtering for the Facebook graph

I am able to retrieve the necessary data from Facebook using the graph API, but I'm struggling to filter out the 'message' and 'id' in JSON format. Here is the code I have been working with: import facebook import json import urll ...

The AJAX request fails to trigger following the onbeforeunload event except when the page is manually refreshed

I'm currently working on implementing a solution for handling the onbeforeunload event to display a custom message when the user tries to close the browser tab. I want a prompt like: Are you sure you want to leave this page? (I don't want to use ...

Is there a way to eliminate a CSS class from a div element within the outcome of an ajax response?

My ajax response is functioning properly and displaying the content of the result, but I am always getting the CSS effects which I do not want. I need to eliminate the class="container body-content" from the following div in the ajax call's result. ...

My website isn't responding to the Ajax call I tried to make

It seems like there might be an issue with my code. I'm working on implementing AJAX for the first time on my website and I believe there is an error with the path... $.ajax({ url: 'http://www.komatpillar.com/ajax/check_email.php ...

Encountered an error with the post request in expess.js: TypeError - Unable to access the property 'fullName' as it is undefined

Hey everyone, I'm new to Express and having trouble posting data from Postman. The error message I'm getting is "TypeError: Cannot read property 'fullName' of undefined". Does anyone have any suggestions on how to fix this? Thank you! ...

What is the best way to add items to arrays with matching titles?

I am currently working on a form that allows for the creation of duplicate sections. After submitting the form, it generates one large object. To better organize the data and make it compatible with my API, I am developing a filter function to group the du ...

React-Redux-Saga: Only plain objects are allowed for actions. Consider using custom middleware for handling asynchronous actions

Struggling to integrate redux-saga into my react app, I keep encountering this error: Actions must be plain objects. Use custom middleware for async actions. The error appears at: 15 | changeText = event => { > 16 | this.props.chan ...

Tips for extracting intricate nested JSON information from an API in React with the assistance of Material UI

Struggling to parse complex nested JSON data retrieved from an API and display it using Material UI in React. Although I can handle basic JSON data, I'm facing challenges with nested structures. JSON Data: { "id": 116, "user&qu ...

Using Firebase data within a Bootstrap modal interface

Recently, I've been working on a website project where I'm utilizing the Firebase Realtime Database to retrieve user-inserted data and display it as Bootstrap Cards, just like in these images: Firebase Realtime Database - 1st card Firebase Real ...

Finding the Index of Parsed JSON Data in Swift

I'm struggling with creating a loop to check if an employee can perform a specific service. It seems that the code I wrote for accessing the employee's services is not working. The employee data is loaded as JSON into EmployeesData. I believe I n ...