I am trying to achieve something simple, using play framework 2.1 (java):
Post JSON data via jquery, and retrieve it from a controller.
Could you kindly tell me where I am wrong?
It starts from a javascript call:
var object = new Object();
object.title = "Hamlet";
object.author = "Bill";
var jsonData = JSON.parse(JSON.stringify(object));
jsRoutes.controllers.Application.update().ajax({
type : 'POST',
dataType : 'json',
data : jsonData,
success : function(data) {
// I get the success
},
error : function(data) {
alert('error');
}
});
The data seems to be correctly posted: Firebug console:
Headers:
Response Headers
Content-Length 2
Content-Type text/plain; charset=utf-8
Request Headers
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
... Parameters
Parametersapplication/x-www-form-urlencoded
title Hamlet
author Bill
Source
title=Hamlet&Author=Bill
It routes here:
POST /update controllers.Application.update()
Here is the Application Controller:
@BodyParser.Of(BodyParser.Json.class)
public static Result update() {
JsonNode json = request().body().asJson();
if(json == null){
return badRequest("empty json"); // PROBLEM: THE JSON IS ALWAYS NULL
}
return ok("{}");
}
And the problem I get is I cannot retrieve my parameters from the request. the request() seems empty if i print it :
DefaultRequestBody(None,None,None,None,None,None,true)
Do you see where I am wrong? How could I get the JSON right?
Thanks in advance
I had exactly the same issue. Besides the dataType
, you have to set contentType
as well, as the original poster suggested:
var jsonMsg = JSON.stringify(msg);
jsRoutes.controllers.Application.sendJson().ajax({
type : 'POST',
dataType : 'json',
contentType : 'application/json; charset=utf-8',
data : jsonMsg
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With