What causes a 400 Bad Request error when attempting to send data using jQuery Ajax within the Spring framework

I am facing an issue with submitting JSON data through jQuery AJAX. I have searched for similar problems online, but none of the solutions seem to be working for me.

            $.ajax({
                type : "POST",
                contentType : "application/json",
                url : "save-routes",
                data : JSON.stringify(routeObject),
                dataType : 'json',
                timeout : 100000,
                success : function(status) {
                    console.log("SUCCESS ADDING ROUTE DATA");
                    return status;
                },
                error : function(e) {
                    console.log("ERROR WHILE ADDING ROUTE DATA");
                    return false;
                },
                done : function(e) {
                    console.log("DONE");
                    //return true;
                }
            });

routeObejct Json format:

{name:"value", data:["value1","value2"...]}

spring controller:

    @JsonView(Views.Public.class)
    @RequestMapping(value = "/save-routes", method = RequestMethod.POST)
    public @ResponseBody boolean loadRoutes(@RequestBody Route route) {
        //codes
        return status;
    }

I am consistently receiving this error message:

POST http://localhost:8181/SYBusWebApp/save-route 400 Bad Request 6ms

Route Class:

public class Route {

    @JsonView(Views.Public.class)
    private String name;

    @JsonView(Views.Public.class)
    private ArrayList<stop> routeStops;

    private String updatedRouteName;
    private ArrayList<String> addedRouteStopNames;

    //getters and setters
}

Stop Class:

public class Stop {

    @JsonView(Views.Public.class)
    private String name;

    @JsonView(Views.Public.class)
    private float latitude;

    @JsonView(Views.Public.class)
    private float longitude;

    private String updatedName; 

//getters and setters
}

Answer №1

Your Route object does not appear to be aligning with the JSON data you are sending.

{name:"value", data:["value1","value2"...]}

To properly structure your JSON payload for routeStops, you should include a nested collection of Stop objects:

{
   name:"value", 
   routeStops:[
       {
         "name":"test",
         "latitude": 3.124
       },
       ....
   ],
   ...
}

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

JSON Schema Validator succeeds even with problems

My objective is to construct a schema that includes an array of items, each with a "key" string property that determines changes in the "data" property schema. Here is the schema I am using for validation and the JSON data that I anticipate failing valida ...

``The art of procrastination in HighCharts and the slow dance with

I'm trying to use LazyHighCharts to display JSON data for the last 24 hours, but I'm facing an issue where only the dates are being displayed and not the temperature for each hour of the day. Here is the data structure: {"status": "ok", "data": ...

Steps for registering Ajax Control Toolkit in Global Assembly Cache (GAC)

Could somebody please share the steps to install the ajax control toolkit in GAC using visual studio 2008? Your help would be greatly appreciated. Thank you. ...

Click event triggering smooth scrolling

I am currently working on implementing a smooth scrolling effect using the React JavaScript library without relying on jQuery. My goal is to ensure that when a user clicks on a link, they are directed to the specific section of the page seamlessly. The f ...

Looping through alert items

Below is the code snippet I am working with: <tr ng-repeat="sce in users"> <td> <a href="/test/delete?id={{sce.id}}" onclick="return confirm('You really want to delete'+ {{sce.name}} + 'from list');" > ...

Appropriate occasion for a concealed field in the user interface grid

Currently, I am utilizing the ui grid feature. Within this feature, there is an option called hide column. I am interested in receiving an event when a user hides a column. Specifically, I would like to display an alert when a column is hidden. Is there a ...

Click the button to automatically generate a serial number on the form

My form includes three input fields: sl no, stationerytype, and stationeryqty. By clicking the symbols + and -, I can add or delete these fields. I am attempting to automatically generate a Sl no in the sl no field when I click the plus symbol, and adjust ...

Image transformed by hovering effect

I've been attempting to add a hover effect to the images in my WordPress theme. The images are displayed in a grid format, created by the featured image on the posts. The grid layout is controlled within content.php <?php /** * controls main gri ...

Challenges Encountered when Parsing JSON with iPhone SDK

Currently, I've been utilizing the SBJSONParser in my iPhone app to parse simple JSON strings like: ["Business1","Business2"] However, I'm now faced with a new challenge where I need to extract both the business name and business ID from the dat ...

How can data be transferred between web pages using jQuery or JavaScript?

Imagine having two different pages on a Classified car website: The first page is the search page, which displays a list of all cars. Check out a sample search page here The second page is the details page, where you can find specific information about a ...

Determine the specified keys within a JSON object using Python

My goal is to generate JSON output that includes a list of MAC addresses and corresponding timestamps for each address. Here's an example of the desired output: [ "B2:C7:23:10:A0": [ "2014-04-04T21:30:46.348900800Z", "2014-04-04T21:30:46.348 ...

"Learn how to extract the image URL from the configuration file (config.json) within the assets folder, and then seamlessly display it within

In my Angular project, I have a configuration file located in the assets folder: { "brandConfig": "brand1", "brand1": {"urlPath": "http://192.168.168.60:8081/mantle-services", " ...

An undefined variable in Angular 2's evaluation

I am currently working with the following code: @ViewChild('MondayPicker') MondayPicker; @ViewChild('TuesdayPicker') TuesdayPicker; @ViewChild('WednesdayPicker') WednesdayPicker; @ViewChild('ThursdayPicker') Thursda ...

What is the process for activating an event before another event on the same element with vanilla JavaScript?

Having an issue with the eventListener function. I am using the external library jquery.jstree-pre1.0fix2, which triggers a blur event on an input in my case. However, I need to trigger my event before the one from the library. I have come across some sol ...

Trouble with binding to an array inside a Vue component instance

Trying to grasp the concepts of vue.js, but struggling with a crucial element. The goal is to create an accordion functionality for multiple boxes (only one box displayed at a time; opening a new box closes any previously open ones). Here's the curre ...

Converting an object with a combination of different index types into a string representation

I'm dealing with a unique object structure that behaves similarly to an array, except it contains a mix of index types (numbers and strings). Here's an example: var myObj = []; myObj[0] = 'a'; myObj[1] = 'b'; myObj[2] = &apos ...

What is the process for deleting certain code from a main component within a React webpage without altering the main component itself?

I have a main component named Layout.jsx that includes the essential elements for the website such as the navigation bar and meta tags. It also contains a Google tag to track analytics across the entire site. Now, I have a specific webpage for Google Ads w ...

Joi has decided against incorporating custom operators into their extended features

I am having trouble extending the joi class with custom operators. My goal is to validate MongoDB Ids, but when I try to use the extended object, I encounter the following error: error: uncaughtException: JoiObj.string(...).objectId is not a function TypeE ...

Retrieve a JSON object from a URL by utilizing the Facebook Graph API within a Ruby on Rails environment

Does anyone know how I can fetch the JSON object from a URL in my Ruby on Rails code? url = "https://graph.facebook.com/me/friends?access_token=XXX" I've been struggling to find a comprehensive tutorial for using JSON with Ruby on Rails. Any help wo ...

Universal approach for transforming a JSON string into a collection of objects

I am trying to develop a generic method that converts a JSON string into a List of objects. fun convertJsonStringToObjectList(jsonString: String , clazz: Class<Any>) :List<Any>{ val gson = Gson() val objectList = gson.fromJson ...