JavaScript object conversion to Java Model is proving to be a challenge

When looking at my Spring controller and client-side Javascript code, I noticed that the Javascript object is having trouble reaching the Spring controller in Object form. Here is a snippet of my Controller code:

@RequestMapping(value = "/addRating", method = RequestMethod.POST, headers = "Accept=application/json")
public EmployeeRating addRating(@ModelAttribute("employeeRating") EmployeeRating employeeRating) {  
    if(employeeRating.getId()==0)
    {
        employeeRatingService.addRating(employeeRating);
    }
    else
    {   
        employeeRatingService.updateRating(employeeRating);
    }

    return employeeRating;
}

And here is a glimpse of my Javascript code:

$.ajax({
          url: 'https://myrestURL/addRating',
          type: 'POST',
          dataType: 'json',
          data: {
              'id':5,
              'name': 'Name',
              'rating': '1'
          },
          contentType: 'application/json; charset=utf-8',
          success: function (result) {
             // CallBack(result);
             window.alert("Result: " + result);
          },
          error: function (error) {
              window.alert("Error: " + error);
          }
      });

The Java EmployeeRating object entails id, name, and rating fields which should align perfectly with the setup.


I decided to update the model class structure:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/* 
 * This represents our model class corresponding to the Country table in the database
 */
@Entity
@Table(name="EMPLOYEERATING")
public class EmployeeRating {

@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
int id;

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

@Column(name="rating")
long rating;

public EmployeeRating() {
    super();
}
public EmployeeRating(int i, String name,long rating) {
    super();
    this.id = i;
    this.name = name;
    this.rating=rating;
}
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public long getRating() {
    return rating;
}
public void setRating(long rating) {
    this.rating = rating;
}   

}

Answer №1

contentType is used to specify the type of data being sent, such as application/json. The default value is set to

application/x-www-form-urlencoded; charset=UTF-8
.

When using application/json, you must utilize JSON.stringify() to send a JSON object.

JSON.stringify() converts a JavaScript object into a JSON text and stores it as a string.

$.ajax({
      url: 'https://myrestURL/addRating',
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify({
          'id':5,
          'name': 'Name',
          'rating': '1'
      }),
      contentType: 'application/json; charset=utf-8',
      success: function (result) {
         // CallBack(result);
         window.alert("Result: " + result);
      },
      error: function (error) {
          window.alert("Error: " + error);
      }
  });

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

Ways to merge values across multiple arrays

There is a method to retrieve all unique properties from an array, demonstrated by the following code: var people = [{ "name": "John", "age": 30 }, { "name": "Anna", "job": true }, { "name": "Peter", "age": 35 }]; var result = []; people. ...

securing data with javascript object encryption

let User = {}; User.username = e.row.username; User.email = e.row.email; User.password = e.row.password; Here is my user object, which I want to store in a file. But before saving it, I need to encrypt the data for security reasons. When reading the file, ...

Determine whether any incoming calls were not answered

Registering a broadcast receiver for incoming call events, I encountered an issue where I needed to determine if an idle incoming call was a Missed Call rather than a rejected one. To accomplish this, I accessed the CallLog provider to retrieve the latest ...

The PHP file is encountering an incomplete $_POST value

Hello everyone, I'm facing a confusing issue with the values of my form. Initially, I created a basic HTML form and converted the values to a string in my document.ready function. Here is a snippet of the code: var fbid = $("#fbid").val(); var ...

Identify Bootstrap modal to modify destination of keypress input

I am working on a piece of code that detects keypress events and focuses input towards a searchbar with the id "search". $( document ).keypress(function() { $("#search").focus(); In addition, I have a bootstrap modal dialog containing input fields ...

When a table row is selected, set the OnClick attribute of an input to the value of the TD cell in that row based on

I'm really struggling with this. So, here's the issue - I have a table where rows get assigned a class (selected) when clicked on. Now, there's an input inside a form that needs to redirect to another page when clicked, and it also needs t ...

React-router-dom v6 causing MUI Drawer to not render

I have implemented ReactJS and I am working on incorporating a drawer/menu to display different routes on each page. I have set up the routes using react-router-dom@v6 in my index.js file. When I directly enter the URL for a specific page, I can see the co ...

Troubleshooting Laravel: Ajax Call for Deleting Records not Functioning Properly on Button Click Event

I've encountered an issue with deleting a record from an ajax call in a Laravel CRUD application. The click event doesn't seem to be triggered, resulting in the delete function not working as intended. Below is the relevant code snippet. web.php ...

Activate continuous speech identification

Is it possible to activate the capability of recognizing continuous speech through the REST API (using javascript SDK) with the Bing Speech API? The Javascript SDK example available at https://github.com/Microsoft/Cognitive-Speech-STT-JavaScript only seem ...

Hover over the first element to remove its class and replace it with a different element

I am attempting to develop a function that adds the class = "actived" to the first Element. This class has a CSS style that highlights the element in question. I have a list of 4 lines and I want the first one to automatically receive this class, while t ...

Send both file and model data using AngularJS with FormData

When uploading an image using the file input type along with other user data, my model includes the User class: public class User { public int Id { get; set; } public string Name { get; set; } public int Rollno { get; set; } public byte[] ...

Using Jquery to generate key value pairs from a form that is submitted dynamically

I'm still learning the ropes of jquery and struggling with a specific issue. I'm looking for a way to dynamically set key:value pairs in the code below based on form inputs that have variable values. The code works when I manually add the key:va ...

Submitting forms that contain files using jQuery and AJAX

Despite searching through numerous questions on this topic, I have yet to find a solution to my specific issue. My objective is to successfully submit an entire form, potentially containing files as well. The code I currently have is not working: $(target ...

"Experience a unique website layout with varying designs on desktop and mobile devices while using the React technology to enable desktop

Just starting out with React and I've noticed something strange. When I view my website on a PC, everything looks normal. However, when I switch to the desktop site on my phone, things appear differently. It seems like moving an element by 20px on mob ...

"Exploring the power of Node.js Virtual Machines and the magic of

I'm currently facing a challenge with reading and extracting data from a dynamically generated HTML file that contains a commented out JavaScript object. My goal is to retrieve this object as a string and execute it using VM's runInNewContext(). ...

Ways to effectively test a custom hook event using Enzyme and Jest: A guide on testing the useKeyPress hook

Looking for guidance on testing a custom hook event called useKeyPress with Enzyme and Jest This is my current custom hook for capturing keyboard events and updating keyPress value: import React, { useEffect, useState } from 'react' const useKe ...

Adding days to a HijriDate: A step-by-step guide

I need help with two text boxes. The first box is for selecting the StartDate from an Islamic calendar, which I am currently using jQuery Calendars Datepicker for. The second textbox, ExpireDate, should automatically be set to 60 days after the selected St ...

Using a variable as a URL parameter in a jQuery ajax request: tips and tricks

$.ajax({ type:"POST", url:"hostname/projfolder/webservice.php?callback=statusReturn&content="+str_table, contentType: "application/json; charset=utf-8", crossDomain:true, dataType:'jsonp', succe ...

Code in JavaScript often includes the use of variables to store and manipulate data

Do these blocks of JavaScript code serve the same purpose? // First Code Sample var first = prompt("Enter the first number:"); var second = prompt("Enter the second number:"); var sum = Number(first) + Number(second); alert(sum); // Second Code Sample ...

Updating DOM element value from controller in AngularJs following an AJAX request

Currently, I am facing an issue in my code where I want to display a progress bar and hide it until isLoaded becomes true. <uib-progressbar class="progress-striped active" value="100" type="warning" ng-hide="{{isLoaded}}"></uib-progressbar> I ...