Error 400 (Bad Request) is returned by the put method in Ionic/AngularJS with an object object shown in the response

I've created a basic Web API along with an ionic/angularJs Client to perform CRUD operations. However, I encountered an error when attempting to edit data on the server.

Below is an image showcasing the data format being sent and the error received:

https://i.sstatic.net/RL4kF.png

Here is the angularJS method for updating:

$scope.save = function (location) {
        var obj = {
            //locationId: $scope.id,
            locationName: location.locationName,
            locationDescription: location.locationDescription
        };

        console.log('output: ' + JSON.stringify(obj));
        $http.put(ServerPath + "/" + $scope.id, $scope.id, obj).success(function (data) {

            $state.go('tab.home');
        }).error(function (data) {
            $scope.error = "An error has occurred while updating! " + data;
            console.log('Error: ' + data);
        });
    };

Answer №1

After making some adjustments to the code, it finally worked as expected.

$scope.save = function (location) {

        var updatedLocation = {
            locationId: $scope.id,
            locationName: location.locationName,
            locationDescription: location.locationDescription
        };

        $http({
            method: 'PUT',
            url: ServerPath + "/" + $scope.id,
            data: JSON.stringify(updatedLocation),
            headers: {
                'Content-Type': 'application/json'
            }
        }).
        success(function (data, status, headers, config) {
            $state.go('tab.home');
        }).
        error(function (data, status, headers, config) {
            console.log('Error: ' + status);
        });

Answer №2

During a demonstration using $http&$resource&postman to issue a PUT request, I encountered the following error message:

ionic.bundle.js:23826 PUT http://localhost:8100/api/users/1?access_token=97d3258a-5a4e-4af4-bd87-3bb9bbb0039f 400 (Bad Request)

After researching for a few days and conducting numerous experiments, I finally discovered that the issue stemmed from the way my bean class was structured:

class User implements Serializable {
    private static final long serialVersionUID = 1L;

    private Integer id;
    private String name;

    public User(Integer id, String name) {
        this.id = id;
        this.name = name;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

Upon removing the constructor's definition or adding a non-parameter constructor, the issue was resolved.

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

Can you identify any issues with this Javascript code's "If" condition?

In my JavaScript code, I have an "if condition" that looks like this: for (var i in data) { //Gender.push("Gender " + data[i].JenisKelaminID); if (data[i].JenisKelaminID == 1) { Gender.push("Men"); } if (data[i].JenisKelaminID == 2) { Gend ...

React Native: Troubleshooting Issue with Shallow Copying of Nested JSON Objects

I have a JSON structure with nested objects like this: {"name", "children": [JSON objects]}. I am attempting to add a new child to the object based on a variable path, which is an array of names. Strangely, my code works fine in the Ch ...

What is the reason that the slick slider is unable to remove the class filter?

Having troubles with my slickUnfilter function, even though slickFilter is working perfectly? Here's a snippet of my HTML: <div class="slider-wrapper" id="wrapper"> <div class="post" id="post1"&g ...

Preserve the height of the previous div following an AJAX request

I am currently facing an issue where I have a script that utilizes ajax to receive a response containing a cart string (html code) with items from the cart. Inside the response handler, there is another script that sets the height of each div in the cart s ...

Encountering an Internal Server Error while setting up a Next.js Application

I recently decided to dive into Next.js and followed the tutorial on their official website, but unfortunately, I hit a roadblock. When I run npm run dev, I encounter the following error messages in my console and terminal: Failed to load resource: the ser ...

Detecting Scroll on Window for Specific Element using Jquery

I need help troubleshooting my code. I am trying to activate only one item that comes from the bottom of the page, but instead all div elements are getting activated. $(window).scroll(function() { $('.parallax').each(function(e) { if($( ...

Utilizing Vue's v-for directive to display computed properties once they have been fully loaded

Utilizing the v-for directive to loop through a computed property, which is dependent on a data attribute initialized as null. I'm planning to load it during the beforeMount lifecycle hook. Here's a simplified version of the code: <th v-for= ...

Displaying divs depending on dropdown selection - Troubleshooting script issue

When I try to display certain divs based on dropdown selection using the script below, it works fine on a simple page. However, when I implement it on my current development page, it completely messes up the layout, turning everything black and adding stra ...

How can I implement a search box on my HTML website without relying on Google Custom Search?

Greetings to all! I am currently managing a website filled with HTML content. I am looking to incorporate a search box into the site. After researching on Google, most of the results point towards using Google Custom Search. However, I require a search box ...

I'm curious as to why my array is only being filled within the subscription function

When I call the GetAllMainStore() function, data is successfully retrieved from the API and the console indicates that "this.MainStoreArray" contains data. The problem arises when I attempt to access "this.MainStoreArray" outside of the GetAllMainStore() ...

Issue with React Hook Form - frequent failure in submitting the form

I have implemented the useForm hook from https://www.npmjs.com/package/react-hook-form. However, I am encountering some inconsistent behavior where it sometimes works immediately, sometimes requires a page refresh to work, and sometimes doesn't work a ...

Troubleshooting problem with jQuery's .has() and .click() functions

I have created a lengthy html code: <div id="el"> <p data-skip>Blablabla</p> // On click, toggle this, and toggle next p <p data-skip>Blablabla</p> // On click, toggle this, and toggle next p <p data-skip>Bl ...

Datagrid in AngularJS does not update filters upon refresh

Currently, I am attempting to implement name filtering with Angular JS using the following library: https://github.com/angular-data-grid/angular-data-grid.github.io. However, an issue arises when searching as the results do not refresh immediately; only up ...

React and React Router are causing the login screen layout to persistently display

The MUI Theme Provider I have includes a Layout with Dashboard and Order screens. Even though the user hits the '/' endpoint, the Login Screen should be displayed instead of the Layout. -App.js <ThemeProvider theme={theme}> <Router> ...

Creating Dynamic Height for Div Based on Another Element's Height Using ReactJS and CSS

I'm attempting to set a fixed height for a div in order to enable overflow scrolling. However, I am encountering issues as I am using JavaScript within a useEffect hook to accomplish this task. The problem is inconsistent as sometimes the height is se ...

Ways to determine if an image has a designated width/height using JavaScript (jQuery)

Similar Question: How can I retrieve the height and width of an image using JavaScript? Typically, we can determine the image width using $('img').width() or $('img').css('width') when a width is specified as shown below ...

struggling to send variables to jade templates with coffeescript and express.js

As a newcomer to node and express, I am currently building the front end of an application that utilizes jade as its templating engine. Despite extensive searching online and within this community, I have not been able to find a solution to a particular is ...

Tips for implementing the JSON object table filter functionality

My website features a collection of json objects organized as shown below: [ { "a": true or false, "b": "information", "c": "information", "d": "information", "e": "information" }, ... ] The goal here ...

The .val() function in jQuery can sometimes give different results when used on input elements with placeholder text in Firefox compared to Chrome

After analyzing the given HTML code, I've noticed discrepancies in the values returned by jQuery in Firefox and Chrome: HTML: <input type="text" name="name" id="name" placeholder="Type Here"> <input type="email" name="email" id="email" plac ...

Testing the full stack in AngularJS applications

Is there a way to conduct comprehensive full stack testing for a nodejs/angularjs application? Lately, I have been facing issues with zombiejs where the test results are inconsistent. I am looking for testing methods that replicate user interactions (simi ...