I have following Spring controller mapping:
@RequestMapping(value="/isSomethingHappening", method = RequestMethod.POST)
public @ResponseBody JsonResponse isSomethingHappening(HttpServletRequest httpRequest,@RequestParam("employeeId") String employeeId,
ModelMap model) throws IOException{
If I invoke this as below then I get 400 response.
var requestData = {"employeeId":XYZ.application.employeeId};
XYZ.network.fireAjaxRequestAsync("application/json", "forms/testing/isSomethingHappening", requestData, function(response, status, xhr){
But if I invoke this as below then I get success response.
var requestData = {"employeeId":XYZ.application.employeeId};
XYZ.network.fireAjaxRequestAsync("application/x-www-form-urlencoded", "forms/testing/isSomethingHappening", requestData, function(response, status, xhr){
I figured the fix but I am not able to understand why first one gave me error when my request data object var requestData = {"employeeId":XYZ.application.employeeId};
remained unchanged and I just changed the content type. To me application/json
looks more appropriate content type because my request data is a JSON object.
Also, I have other instances where my controller mapping is as below:
@RequestMapping(value = "/getOnFlyResults", method = RequestMethod.POST)
public @ResponseBody JsonResponse getOnFlyResults(HttpServletRequest httpRequest,
@RequestBody testingRequestVO testingRequestVO, ModelMap modelMap) throws IOException{
And for invoking this, I send request as below:
var requestData = {"employeeId":XYZ.application.employeeId,
"fName":XYZ.application.fName,
"lName": XYZ.application.lName,
"telephoneNumber":telephoneNumber,
"testMode":XYZ.constant.onFly};
XYZ.network.fireAjaxRequestAsync("application/json", "forms/testing/startTest", JSON.stringify(requestData), function(response, status, xhr){
I don't understand that why I have to stringify the data using JSON.stringify(requestData)
, if I do not do this then I will get 400.
Once I stringify then it becomes a string then my content type should have been text/plain
but it works with application/json
Please note that I know the code fixes, but I want to understand the concept. I have read this and it doesn't explain the concept in details and queries I have.