mrchebik mrchebik - 3 months ago 26
Ajax Question

Spring MVC + Ajax JSON post

I have a problem with send

JSON
to the
Controller
. I can't understand my problem.

So, url -
/notes/{username}/add


Ajax:

$.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url: window.location.pathname,
data: JSON.stringify({ title: $("#title").val(), text: $("#text").val() }),
success : function() {
$("#title").val("");
$("#text").val("");
}
});


Controller:

@RequestMapping(value = "/{username}/add", method = POST)
public void add(@RequestBody Note note) {
noteRepository.add(new Note(UserSession.getUser(), note.getTitle(), note.getText()));
}


Note:

public class Note {

private String title;
private String text;

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getText() {
return text;
}

public void setText(String text) {
this.text = text;
}
}


Controller don't get request from ajax. I think, problem with url, but I can't why and what to do.

Answer

Modify your controller as:

@RequestMapping(value = "{username}/add", method = RequestMethod.POST)
public void add(@RequestBody Note note, @PathVariable("username")String username) {
}

And your ajax call url should include the path variable as:

$.ajax({
        type: "POST",
        contentType : 'application/json; charset=utf-8',
        dataType : 'json',
        url : '/Notes/notes/username/add',
        data: JSON.stringify({ title: $("#title").val(), text: $("#text").val() }),
        success : function() {
            $("#title").val("");
            $("#text").val("");
        }
    });

Also make sure your pom.xml or build.gradle should have jackson dependency, below is an example for maven project:

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.3</version>
</dependency>