error when sending request using Spring MVC and Ajax

Spring Controller Method :

    @RequestMapping(value="/checklist/{id}",method=RequestMethod.PUT, consumes=MediaType.APPLICATION_JSON_VALUE , produces=MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Checklist update(@RequestBody Checklist checklist, @PathVariable("id") int id)
    {
        checklist.setId(id);
        return service.update(checklist);

    }

JavaScript AJAX code:

    var checklist={name:$('#newName').val(), details:$('#newDetails').val()};
                    $.ajax({                //send updated item values to
                        method:'put',
                        url:'/tracker/checklist/'+$(editingItem).attr('id'),
                        contentType:'application/json',
                        dataType:'json',
                        data:checklist,
                        success:function(data)
                        {
                            console.log(data);
                            $('#myModal').modal('hide');
                        }
                    });

Checklist Model:

package com.tracker.web.models;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

@Entity
@Table(name="checklists")
public class Checklist {

    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;

    private int item_order;
    private String name;
    private String details;
    private String phase;
    private String completed;
    private String skipped_note;
    private Date completed_on;
    private int completed_by;

    @Temporal(TemporalType.TIMESTAMP)
    @CreationTimestamp
    private Date created_at;

    @Temporal(TemporalType.TIMESTAMP)
    @UpdateTimestamp
    private Date updated_at;

    @ManyToOne
    private Event event;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getItem_order() {
        return item_order;
    }

    public void setItem_order(int item_order) {
        this.item_order = item_order;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDetails() {
        return details;
    }

    public void setDetails(String details) {
        this.details = details;
    }

    public String getPhase() {
        return phase;
    }

    public void setPhase(String phase) {
        this.phase = phase;
    }

    public String getCompleted() {
        return completed;
    }

    public void setCompleted(String completed) {
        this.completed = completed;
    }

    public String getSkipped_note() {
        return skipped_note;
    }

    public void setSkipped_note(String skipped_note) {
        this.skipped_note = skipped_note;
    }

    public Date getCompleted_on() {
        return completed_on;
    }

    public void setCompleted_on(Date completed_on) {
        this.completed_on = completed_on;
    }

    public int getCompleted_by() {
        return completed_by;
    }

    public void setCompleted_by(int completed_by) {
        this.completed_by = completed_by;
    }

    public Date getCreated_at() {
        return created_at;
    }

    public void setCreated_at() {
        this.created_at = new Date();
    }

    public Date getUpdated_at() {
        return updated_at;
    }

    public void setUpdated_at() {
        this.updated_at = new Date();
    }

    public Event getEvent() {
        return event;
    }

    public void setEvent(Event event) {
        this.event = event;
    }

}

I am utilizing Jquery 1.11 version. When I switch 'PUT' to 'GET' on the client side and 'consumes' on the server side, it works. I even attempted using JSON.stringify during the sending process. On the server side, I am using Jackson to convert the data into JSON format.

Answer №1

What version of jQuery are you currently using?

If your version of jQuery is pre-1.9.0, consider using type: 'PUT' instead of method:'put' in your AJAX call to make it work properly. Otherwise, stick with method:'put'.

For more information, consult the documentation at http://api.jquery.com/jquery.ajax/

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

"Unlocking the power of C++ DLL functions in Java: A comprehensive guide for loading, accessing, and

Creating a DLL in C++ that performs basic arithmetic operations is quite simple. The code below demonstrates how to create a Math DLL: Math DLL.cpp #include "Math.h" using namespace std; long addition(long a, long b) { return a + b; } long subtrac ...

The 'v-model' directive necessitates a valid attribute value for the left-hand side (LHS)

I am facing an issue with my Vue application. I have a table where each row has its own unique id. I need to show or hide certain elements based on a condition in the v-model directive which compares the row id with a value in the model. The current code s ...

Insert a fresh directive within an ng-repeat loop

I currently have an array of data that is being shown using a directive within an ng-repeat. Whenever the user clicks on a button, a new object is added to this array which requires a new instance of the directive to be executed. Here is my current HTML se ...

AngularJS Custom Navigation based on User Roles

I am currently developing a small web application using angular. My goal is to implement role-based navigation in the app. However, I am facing an issue where the isAdmin function does not seem to be getting called on page load, resulting in only the foo a ...

The server node proxy is failing to trigger the API call

update 1: After modifying the api path, I am now able to initiate the api call. However, I encountered the following error: (node:13480) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 4): RangeError: Invalid status code: res ...

Mix up the characters in the array to create a new randomized string

My task involves working with a char array of size 12, which can be represented as follows: {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k&a ...

How to generate a fresh date in Java using integer values

Currently utilizing a Date Picker to display and select dates, having some difficulties with the format. The example below shows how it is currently structured. new StringBuilder().append(month + 1) .append("-").append(day).append("-").append(year) .appe ...

Using Javascript to add hovering effects that demonstrate sophistication and style

I have a question : Here is the HTML code snippet: <div class="a b"> <span class="one">Success ONE</span> <span class="two">ONE</span> </div> <div class="a b"> <span class="one">Success TWO< ...

Unable to retrieve Google Maps route on Android device

After discovering the route between two latitude and longitude values on Google Maps using "Get Directions," everything appears accurately. However, when attempting to use the same directions in an Android mobile application, only the destination marker ...

Adjust the prop value whenever there is a modification in the Vuex store

Following a successful mutation to the vuex store (state.posts.post.comments) with the use of this code snippet and implementing Vue.set for Vue to acknowledge the addition of an object property: store/modules/post.js const mutations = { [types.SET_P ...

Is it possible to change cases within a switch statement after one case condition has been satisfied?

I am currently working on implementing a game that involves rolling dice in Javascript/jQuery. The game has different "Phases" that the player must complete one by one without any interference from previous phases. The goal is to smoothly transition betw ...

Error occurred while fetching image from Medium story API in Next.js

While working on my Next.js app, I encountered an issue with the Medium story API. Every time I try to fetch and display an image using the API, I receive an error message stating "upstream image response failed." The specific error code is: upstream image ...

Creating dynamic properties in JavaScript based on another object is a powerful way to manipulate data

In my current scenario, I am faced with the task of creating a new object named result based on an existing object called source. This new object must contain all properties from source, and also include additional "methods" named after the properties to ...

Tips for adjusting the search bar's position on a mobile device when it is activated by the user

I need help with an open source project where I am developing a search engine using Angular. When using smaller screen sizes, the search bar is positioned in the middle but gets hidden behind the keyboard terminal when clicked on. Can anyone advise on ho ...

Use Node and Express with JavaScript to store HTML form data in JSON format within a .json file

Just starting out with node and express. I am capturing user input from an HTML form and attempting to append or push it in a .json file. I tried using the jsonfile npm package but the data is not being stored in an array format in the JSON file. Here is ...

What is the best method for choosing these elements and surrounding them with a wrapper?

I need to style a title with two radio inputs by wrapping them in a form: <p><strong>Country</strong></p> <div class="radioWrapper"> <span class="label">Canada</span> <span class="radio"> ...

Understanding how to set the Content-Type in a Post request using Ajax with Node.js

Attempting to send an ajax request without a header in Node.js triggers an error: { [Error: unsupported content-type] status: 415, statusCode: 415 } However, when sending a request with a header, Node.js does not seem to respond. Here is my ajax funct ...

Saving the selected value from a dynamic dropdown menu in a JavaScript application to a MySQL database

This code successfully saves the values of departments but is encountering an issue with saving the degree value into MySQL. I am currently using PHP for this functionality. Here is the HTML code: <select class ="form-control" name="depa ...

The global variable remains unchanged after the Ajax request is made

I am attempting to utilize AJAX in JavaScript to retrieve two values, use them for calculations globally, and then display the final result. Below are my code snippets. // My calculation functions will be implemented here var value1 = 0; var v ...

Tips on effectively utilizing the generic class type parameter class

One interesting aspect of my work involves a genetic class parameter public static <T> T parse(String json, Class<T> clazz) { T result = null; result = mapper.readValue(json, clazz); return result; } Imagine there is a JSON object l ...