1

I'm currently using spring boot, and i want to send object from ajax to controller for validation. I know you can submit the form normally with ModelAttribute but i want to submit with ajax for validation. But the ajax function return a 400 error or a 415 error everytime, i've tried looking up for solution everywhere but it doesnt help really.

my view :

<form id="Form">
        <input name="id"></input>
        <input name="name"></input>
        <button type="submit" class="btn btn-default" id="button"></button>
    </form>
    <script>
        $(document).ready(function(){
            $("#button").click(function(e){
                e.preventDefault();
                $.ajax({
                    type: "POST",
                    url : "/Test",
                    async: false,
                    dataType : "json",
                    data : $("#Form").serialize(),
                    contentType: "application/json",
                    success : function(result){
                        if(result == null){
                            alert("Succ");
                        }
                        else{
                            alert("not null");
                        }
                    },
                    error : function(){
                        console.log('here');
                        alert($("#Form").serialize());
                    }
                });
            });
        });
    </script>

my controller :

@RequestMapping(value = "/Test",method = RequestMethod.POST)
    public @ResponseBody PersonRequest test(@RequestBody PersonRequest person) {
        return person;
    }

my entity :

public class PersonRequest {

    @NotNull
    private long id;

    @NotEmpty
    private String name;

    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public PersonRequest() {
        super();
    }
}

If i remove contentType: "application/json" from ajax function it returns a 415 error, and if i keep it it returns a 400 error. Please help.

Browser console The IDE console return this following error :

.w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'id': was expecting ('true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'id': was expecting ('true', 'false' or 'null')
 at [Source: java.io.PushbackInputStream@1fc7f789; line: 1, column: 4]
NganCun
  • 155
  • 1
  • 4
  • 13

1 Answers1

1
$.ajax({
  type: "POST",
  url : "/Test",
  async: false,
  dataType : "json",
  data : JSON.stringify({id:"value of Id input", name: "value of name input"}),
  contentType: "application/json",
  success : function(result){
    if(result == null){
        alert("Succ");
    }
    else{
        alert("not null");
    }
  },
  error : function(){
    console.log('here');
    alert($("#Form").serialize());
  }});

The JSON object in request body has to match your backend model PersonRequest

spiritwalker
  • 2,257
  • 14
  • 9
  • is there any way to send the whole form and not having to put every attribute into data{} as you said? because if the object has a lot more attributes it's gonna be hard to do that – NganCun Sep 14 '17 at 06:38
  • @NganCun I updated the answer to stringify json object before post. If terms of constructing a json object from html form, there is an elegant solution already. https://stackoverflow.com/questions/1184624/convert-form-data-to-javascript-object-with-jquery – spiritwalker Sep 14 '17 at 12:27