Reputation: 793
I am sending a form data using AJAX and my Spring MVC controller is getting null
value, but if I use Postman it will work fine.
Here is my ajax call:
$.ajax({
type: "post",
url:"http://localhost:8080/fivenet/mobile/api/login",
crossDomain: true,
data: JSON.stringify(formData),
dataType: 'json',
contentType: 'text/html;charset=UTF-8',
//contentType: 'application/json;charset=utf-8',
beforeSend: function(xhr){
},
success: function(msg){
console.log('sucess');
},
error: function(msg){}
Here is my controller:
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping(value = "create-account", method = RequestMethod.POST)
public @ResponseBody RespondMessage createAccount(
@RequestParam(value = "data", required = true) String dataString,
HttpServletRequest request) throws Exception {
RespondMessage responsed = new RespondMessage();
headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
JSONObject data = new JSONObject(dataString);
return responsed;
}
Upvotes: 2
Views: 1953
Reputation: 793
I have finally solved the problem. Its the way I serve my data.
$.ajax({
type: 'POST',
url: "http://localhost:8080/fivenet/mobile/api/login",
crossDomain: true,
data: {"data": JSON.stringify(formData)},*** This is where the error is
dataType: 'json',
beforeSend: function(xhr){
},
success: function(msg){
console.log('sucess');
},
error: function(msg){}
thanks all for your concerns
Upvotes: 1
Reputation: 4205
Try this code:
var formData = {"username" : "username", "password" : "password"};
$.ajax({
type: "POST",
url: "http://localhost:8080/fivenet/mobile/api/login",
data: JSON.stringify(formData),
dataType: 'json',
contentType: 'application/json;charset=utf-8',
beforeSend: function(xhr){
},
success: function(data){
alert(data)
},
failure: function(errMsg) {
alert(errMsg);
},
error: function(errMsg){
alert(errMsg);
}
Upvotes: 0