2

I'm not sure what's wrong with the way I'm doing this... I get a 400 Error saying it's a bad request, but I can't find anything wrong with my syntax.

$.ajax({
        url : '/my_project/rest/runs/1234?token=moo',
        type : 'POST',
        data: { job_position : JSON.stringify(38) },
        contentType: 'application/json',
        dataType: 'json',
        success : function(html) {
        }
    });

The receiving controller:

@RequestMapping(value="/runs/{userId}", method = RequestMethod.POST, consumes = {"application/json"})
    public @ResponseBody boolean myMethod(@PathVariable String userId, @RequestParam("token") String authenticationToken, @RequestBody @Valid Long job_position){
        return true;
    }
Hanna
  • 10,315
  • 11
  • 56
  • 89

3 Answers3

2

Is your data part missing quotes? data: { "job_position" : JSON.stringify(38) }

Just a thought.

edocetirwi
  • 542
  • 5
  • 22
  • http://stackoverflow.com/questions/949449/json-spec-does-the-key-have-to-be-surrounded-with-quotes says it is a good practice to place quotes and also to guard against reserved words. – edocetirwi Aug 31 '12 at 20:02
  • It is missing quotes, and as radashk mentioned, it's not mandatory. But I have added it now just to be 100% safe. – Hanna Aug 31 '12 at 20:27
2

/my_project/rest/runs/1234?token=moo - it's GET request sintax

make
url : '/my_project/rest/runs/1234'
and
data: { "job_position" : JSON.stringify(38) , "token" : "moo"}

so full request look like

$.ajax({
        url : '/my_project/rest/runs/1234',
        type : 'POST',
        data: { "job_position" : 38, "token" : "moo"},
        contentType: 'application/json',
        dataType: 'json',
        success : function(html) {
        }
    });
Ilya
  • 29,135
  • 19
  • 110
  • 158
  • I get this in my request payload: "job_position=26&token=moo" I also changed my controller, so that I have a single response object that contains a token and a job position. – Hanna Aug 31 '12 at 20:23
1

Your not actually sending JSON in your request, jQuery will convert your object to a query string. To prevent this stringify it yourself.

$.ajax({
        url : '/my_project/rest/runs/1234',
        type : 'POST',
        data: JSON.stringify({ job_position : 38, token: 'moo' }),
        contentType: 'application/json',
        dataType: 'json',
        success : function(html) {
        }
});
Musa
  • 96,336
  • 17
  • 118
  • 137