RRR_J
RRR_J

Reputation: 347

Jquery Ajax POST not working. works fine for GET

I am trying to post jquery Ajax request but it does not go to my MVC controller.

$.ajax({
            url : contextPath + "/check/panelnumber",
            type : "POST",
            contentType : "application/json",               
            data :{
                    "execution" : execution,
                    "panelNumber" : panelNumber
            },
});

Spring MVC controller

@Controller
@RequestMapping("/check")
public class ValidateFieldValueController extends FlowEnabledBaseController {

@RequestMapping(value = "/panelnumber", method = RequestMethod.POST)
public ResponseEntity<String> checkPanelNumber(HttpServletRequest request,
        HttpServletResponse response,
        @RequestParam("panelNumber") String panelNumber,
        @RequestParam("execution") String execution) {
......
Gson gson = new Gson();
return new ResponseEntity<String>(gson.toJson(details), HttpStatus.OK);
}

However it works perfectly fine for GET method! Tried adding dataType: "json" as well but with this even GET call stops working. Browser console shows error as HTTP 400 bad request but when checked through firefox plugins the POST parameters are going fine. Any help?

Upvotes: 0

Views: 233

Answers (1)

xathien
xathien

Reputation: 822

Spring is a little touchy when it comes to @RequestParam, POST body, and JSON content-type: it simply won't parse them. You can solve this problem one of three ways:

  1. Change the content-type to be application/x-www-form-urlencoded
  2. Change the two @RequestParam to be a single @RequestBody Map<String, Object> body, then use that Map to manually parse out your parameters.
  3. Set up a custom Argument Resolver that can parse JSON for your desired values.

The second method is likely the easiest to change, but it loses you some of the automagic validation that Spring does for you.

Upvotes: 2

Related Questions