Reputation: 59
I am trying to submit my form to the controller as JSON data to be further processed. I am using jquery to and use following code to submit the data:
My js code:
$(document).ready(function(){
alert('hi');
$("#btn-save").click(function(event) {
var data = {}
alert($("#name").val());
data["name"] = $("#name").val();
data["address"] = $("#address").val();
data["phone"] = $("#phone").val();
data["zipCode"] = $("#zipCode").val();
$("#btn-save").prop("disabled", true);
alert('1'+JSON.stringify(data));
$.ajax({
type: "POST",
contentType: "application/json",
url: "/saveUser",
data: JSON.stringify(data),
dataType: 'json',
timeout: 600000,
success: function (data) {
alert('success');
},
error: function(xhr, status, error){
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage);
}
});
});
});
</script>
I have written my controller class which is expected to handle the requests. but the execution never reaches this method. This is expected to call the controller class:
@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
public @ResponseBody SysUserDto saveUser(@RequestBody SysUserDto user) {
System.out.println("Save code******");
return user;
}
I even tried with out response body and having the return as void instead of SysUserDto But i see 404 error as the execution goes to error block. Please help
Upvotes: 1
Views: 69
Reputation: 118
You can tried this. assuming your form id is called 'uploadForm'
$(document).ready(function(){
alert('hi');
$("#btn-save").click(function(event) {
event.preventDefault();
var user= new FormData($('#uploadForm')[0]);
$.ajax({
contentType : false,
processData : false,
type: 'POST',
url: "/saveUser",
data: user,
timeout: 600000,
success: function (data) {
alert('success');
},
error: function(xhr, status, error){
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage);
}
});
});
});
</script>
controller:
@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
public @ResponseBody String saveUser(SysUserDto user) {
System.out.println("Save code******");
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(user);
System.out.println(json);
return json;
}
ObjectMapper
is from jackson library.
Upvotes: 1