"Mastering the art of sending a request to the server using AJAX with the

Here is some of my code in HTML:

function loadDoc(){
 var num = '{"empid": 45,"name": "gaurav","salary":566.55}';
  $.ajax({

url: 'http://localhost:9029/addS',
method: 'POST',
data: num,
success: function(response){
      console.log("response::::"+response);
      $("#output").text(response);
},

error: function( jqXHR,textStatus, errorThrown){

    console.log("Error askdjk");
    console.log(jqXHR);
    console.log(textStatus);
    console.log(errorThrown);
}

  });   
}

And here is a snippet from my Java code:

@RequestMapping(value="/addS",method={RequestMethod.POST})

public String addEmployee(@RequestParam int empid,@RequestParam String name,@RequestParam double salary){

return "employee added successfully(Separate): "+name;
}

I'm encountering a 400 error and despite trying multiple solutions, I am unable to resolve it. Any help would be appreciated.

Answer №1

In my opinion, creating an object for the request body would be beneficial. Here is an example:

public class Employee {
    public int empId;
    public String name;
    public double salary;
}

After defining the object, you can use @RequestBody annotation in your method:

@RequestMapping(value="/addEmployee", method={RequestMethod.POST})
public String addEmployee(@RequestBody Employee employee) {
    return "Employee added successfully: " + employee.name;
}

Alternatively, consider modifying your AJAX code to utilize a GET request instead.

Answer №2

Perhaps you should consider using data: JSON.stringify(num) in place of data: num for your ajax call.

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

Issue with Ionic displaying data from AngularJS $http.get request

Having just started learning AngularJS, I have followed tutorials on YouTube and read the documentation, but I am struggling to display data from an API using the $http.get() request. Here is my JavaScript and HTML code: var exampleApp= angular.modul ...

Ways to assess the efficiency of the client browser using JavaScript

As I work on creating my website, I have come across an issue with lag when scrolling through a certain viewport that contains a canvas element. To address this problem, I am looking to analyze the browser's performance, specifically focusing on the f ...

Sending JavaScript data to PHP on the same page

I've developed a simple code to transfer a JS variable to PHP on the same page. Here is the code I have implemented: <body> <h3>Client side IP geolocation using <a href="http://ipinfo.io">ipinfo.io</a></h3> ...

Angular 4 with Typescript allows for the quick and easy deletion of multiple selected rows

I am currently working on an application where I need to create a function that will delete the selected checkboxes from an array. I have managed to log the number of checkboxes that are selected, but I am struggling to retrieve the index numbers of these ...

Attempting to eliminate Roman numerals and numerical values from a list of Strings

In my quest to cleanse a text file of the story "Robin Hood", I am facing the challenge of eliminating elements such as "I.", "II.", "279" (page numbers and chapters), etc. The obstacle lies in removing these numerical values from the string arraylist. fo ...

Angular Unit testing error: Unable to find a matching route for URL segment 'home/advisor'

Currently, I am working on unit testing within my Angular 4.0.0 application. In one of the methods in my component, I am manually routing using the following code: method(){ .... this.navigateTo('/home/advisor'); .... } The navigateTo funct ...

Retrieve a document through Django's rest framework after verifying the user's credentials

Currently, I'm immersed in a project employing Django as the backend. My focus lies on utilizing Django Rest Framework to manage an API for downloading files. @detail_route(methods=['GET'], permission_classes=[IsAuthenticated]) def test(sel ...

Using jQuery to identify keydown events in ASP.NET

Within the context of my project, there is a search button that automatically triggers when the ENTER key is pressed. How can I use jQuery to detect a keydown event specifically for a login button in an ASP.NET project? ...

How to Toggle the :invalid State to True on a Dropdown Element Using JQuery

$("#select_id").is(':invalid') false Is there a way to change it to true? $("#select_id").addClass(':invalid'); $("#select_id").prop('invalid',true) Unfortunately, this method does not seem t ...

Interactive radio button selection with dynamic image swapping feature

I'm currently working on creating a radio list with three options: Salad Spaghetti Ice cream This is how I coded it: <div id="radiobuttons"> <label><input name="vf" type="radio" value="0" checked/>Salad</label> < ...

Maintaining duplicate values in a JSON stringify operation: Tips for retention

Server responses are being received in JSON format, which may contain objects with duplicate keys. When displaying the results, I noticed that only the last value for duplicate keys was showing up. After investigating, I realized this was due to using the ...

Is there a way to capture an error message in the JSON fetch response?

Here is the code snippet to consider: fetch('https://api.flickr.com/services/rest/?method=flickr.photos.search' + '&api_key=thiskeyshouldgivemeanerror&text=dog&format=json' + '&per_page=24&nojsoncallbac ...

Transforming a text file into an array using fs in Node.js

My text file contains the following: {"date":"2013/06/26","statement":"insert","nombre":1} {"date":"2013/06/26","statement":"insert","nombre":1} {"date":"2013/06/26","statement":"select","nombre":4} Is there a way to convert the text file contents ...

Changing SOAP multiref into a Java object

Could you assist me in converting the SOAP request data into a Java Collection? I have attempted it but did not achieve the desired result. Please refer to the second part below where I successfully transformed Java data into a SOAP request. <multiRef ...

Is it possible to use the addRow function with AJAX in Tabulator, similar to how setData is

Currently working with Tabulator 3.5 and I have a question... Can I dynamically add a row to tabulator using AJAX to get the data, similar to how we set data using setData? For example, instead of: $("#picks-table").tabulator("addRow", {"player":"La Di ...

Is it possible to utilize Class objects within Google Apps Script Libraries?

Recently, I've been working on a JavaScript class that looks like this: class MyObject { constructor(arg1, arg2, arg3) { this.field1 = arg1; this.field2 = arg2; this.field3 = arg3; } myMethod(param1, param2) { return param + par ...

Styling the content within Template Strings is not supported by VSCode

Recently, I've noticed that there are two scenarios in which my VSCode doesn't properly style the content within my template strings. One is when I'm writing CSS in a JavaScript file, and the other is when I'm fetching data from GraphQL ...

Utilize Protractor Selenium to extract content from a popup window

Having trouble capturing the text from a popup using Protractor with getText? The HTML structure can be found here. This popup only appears for a few seconds before disappearing. Can anyone assist me in retrieving the text from this popup? To retrieve the ...

Developing secure web applications using Node.js and Express with HTTPS encryption

I am attempting to utilize express with node.js using https. Below is the relevant code for this segment: var express = require("express"); var app = express(); var https = require('https'); var privateKey = fs.readFileSync('./sslcert/myke ...

Sending Paypal IPN Data to Node.JS: A Step-by-Step Guide

I'm looking to implement a real-time donation system on my website that can update all users simultaneously. The challenge I'm facing is that the IPN (Instant Payment Notification) page, responsible for verifying payments, is written in PHP. Unf ...