[play 2.0 scala] jQuery ajax - JSON body parsing and json content Type

1,017 views
Skip to first unread message

Arun Ramakrishnan

unread,
Jun 1, 2012, 5:45:37 PM6/1/12
to play-fr...@googlegroups.com
I am not sure this involves how play parses json or if it is a pure jQuery/JS problem.

I am having trouble sending json object as part of a json cotent-Type POST request.

JavaScript/jQuery

var data1 = ({ rating : 3 }) ; // does not work 
var data2 = '{ "rating" : 3}'; // works fine

$
.ajax( { url : "/rate", data : data1 , contentType: "application/json", success: function(json){ console.log("Ajax Return :"+json); } } );

When I use data1 in place of data2 I get a 400 (Bad Request)

routes
POST     /rate   controllers.Application.rate

The action code is like this
def rate = Action(parse.json) { request =>  Ok(toJson( Map("success":1) ));  }


thanks
Arun

Arun Ramakrishnan

unread,
Jun 1, 2012, 5:50:43 PM6/1/12
to play-fr...@googlegroups.com
it is a POST request to be more explicit/

$
.ajax( { url : "/rate", data : data1 , type: "POST", contentType: "application/json", success: function(json){ console.log("Ajax Return:"+json); } } );

Durgesh Mankekar

unread,
Jun 1, 2012, 6:06:45 PM6/1/12
to play-fr...@googlegroups.com
You could try wrapping data1 in JSON.stringify

data: JSON.stringify(data1)

-Durgesh

--
You received this message because you are subscribed to the Google Groups "play-framework" group.
To post to this group, send email to play-fr...@googlegroups.com.
To unsubscribe from this group, send email to play-framewor...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/play-framework?hl=en.

Arun Ramakrishnan

unread,
Jun 1, 2012, 6:44:32 PM6/1/12
to play-fr...@googlegroups.com
thanks. Thats what i did.

Interestingly, even if you explicitly specify { contentType : "application/json" } in the ajax method call, only the appropriate header is set, the JS object you pass as value for the data parameter is not converted to a JSON string ( one always hopes for more intelligence ), but still gets encoded as url-form-encoding. So, one has to explicitly convert the JS object to JSON string.

thanks
Arun
Reply all
Reply to author
Forward
0 new messages