Sending JSON Data to Server Error
Solution 1
Problem was about the JSON array. It was not a valid JSON string that was sent from client to server.
Edit
To clarify this, I stumbled upon this post. It is required to do a proper JSON.stringify(data)
in the Ajax request. It's strange but it's not done by the .ajax
function when setting the corresponding dataType
.
$.ajax({
async : false,
type:'POST',
url: '/uxiy/webapp/uxmer',
data: JSON.stringify(user),
dataType: 'json',
success: function(data) {
...
},
error: function(data) {
...
}
});
Solution 2
Set the content type to application/json
or Jackson won't kick in.
$.ajax({
async : false,
type:'POST',
contentType: 'application/json',
url: '/uxiy/webapp/uxmer',
data: user,
dataType: 'json',
success: function(data) {
...
},
error: function(data) {
...
}
});
kamaci
Updated on June 04, 2022Comments
-
kamaci almost 2 years
I want to sent a JSON data to my controller's POST handler. I do that at my client side:
var userName = $('#userName').val(); var password = $('#password').val(); var mail = $('#mail').val(); var admin =$("#admin").is(':checked'); var user = {userName: userName, password: password, mail: mail, admin:admin}; $.ajax({ async : false, type:'POST', url: '/uxiy/webapp/uxmer', data: user, dataType: 'json', success: function(data) { ... }, error: function(data) { ... } });
My Spring controller as follows:
@RequestMapping(method = RequestMethod.POST) public void createUser(HttpServletResponse response, @RequestBody User user) { user.setName("POST worked"); //todo If error occurs response.sendError(HttpServletResponse.SC_NOT_FOUND); response.setStatus(HttpServletResponse.SC_OK); }
However when I send my data I get that error at Firebug:
"NetworkError: 415 Unsupported Media Type"
What is wrong?
PS: An example of Firebug POST details:
Parameters application/x-www-form-urlencoded admin true mail [email protected] password r userName userx Source userName=userx&password=r&mail=user%40user.com&admin=true
PS2: After I added
contentType: 'application/json',
it started to give
"NetworkError: 400 Bad Request"
What can be the problem, making serialization, etc?
PS3: Here: http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/ it says:
If there are validation errors, a HTTP 400 is returned with the error messages, otherwise a HTTP 200 is returned.
I have 400 Bad Request Error. Maybe the problem is related to that?