400 Bad Request Response for AJAX Request

I have the following jQuery AJAX request:

// collect form data and create user obj var user = new User(); user.firstname = $("#usrFirstName").val(); user.lastname = $("#usrSurname").val(); user.role = $("#usrRole").val(); // actual ajax request $.ajax({ type: 'POST', url : 'http://awesome-url', crossDomain: true, data: user, contentType:"application/json; charset=utf-8", dataType: 'json' }).done(function(data, status) { alert(JSON.stringify(data)); }).fail(function(data, status) { alert(status); alert(JSON.stringify(data)); }); 

Server response:

"status": 400, "statusText": "Bad request"
"The request sent by the client was syntactically incorrect."

Server runs Spring-MVC. But as far as I can tell, it works correctly. Because if I send the request manually using Postman and the following configuration, it works.

Title:

 Content-Type application/json; charset=utf-8 

Content:

 {"firstname":"alex","lastname":"lala","role":"admin"} 

I should mention that this is a cross-domain request (to develop the time, it will be placed in the same domain as the server later). I disabled the security settings in the browser and the AJAX requests to the server are working fine (so far I do not need to send data).

+7
javascript jquery spring-mvc
source share
1 answer

you need to serialize your json, try:

 $.ajax({ type: 'POST', url : 'http://awesome-url', crossDomain: true, data: JSON.stringify(user), contentType:'application/json; charset=utf-8', dataType: 'json' }) 
+6
source share

All Articles