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]