Reputation: 101
I'm trying to call a controller method that will save my object, but when i try to url to it, it returns http error. I've browsed through some similar problems on SO but no luck. So i wanna ask myself...
Here is my Ajax (for simplicity purposes i renamed the variables):
function addDob() {
var var1 = $("#var1").val();
var var2 = $("#var1").val();
var var3 = {};
var3["var3"] = $("#var3").val();
var json = JSON.stringify({
var1 : var1,
var2 : var2,
var3 : var3
});
console.log(json);
alert(json);
$.ajax({
url: 'add_dob',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: json,
success: function (data) {
console.log(json);
alert(data.message);
resetForm();
},
error: function () {
alert("Error!");
}
});
}
Here is my controller:
@RequestMapping(value = "/add_dob", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public Map<String, Object> saveDob(@RequestBody DobavljacWrapper wrapper) {
Map<String, Object> data = new HashMap<>();
Dob d = new Dob();
d.setCountryID(wrapper.getCountryID());
d.setDobName(wrapper.getDobName());
d.setYear(wrapper.getYear());
dobService.save(d);
data.put("message", "Dob was successfully saved!");
return data;
}
Any suggestion is welcomed. If i need to insert any more info, just let me know. Cheers! P.S. I had a similar project that works, but my model classes were different, so i suspect there's something to it..
UPDATE 1.0:
I figured out it has a lot to do with the @RequestBody parameter.
That parameter matches the one you are pushing through with your Ajax. Now, I need that parameter to match my object which has the exact attributes I am passing through with Ajax. Somewhere in there i am making a mistake, and i'm not sure what exactly is the right way here...
If i set "@RequestBody String someString" it will return the parameters i pushed with ajax, but i won't be able to access that info with the getters 'cause it's a string. So i need an object to collect those values!
Upvotes: 7
Views: 86648
Reputation: 101
The answer was the Wrapper class. It couldn't assign values to it and threw error because i set attributes to "private". Setting them "public" solved it for me.
Can't believe that was the error...
Upvotes: 3