Reputation: 2165
I'm new to play and I am trying to post form data to my Play Action using JQuery. However, I'm getting "expected json" response from Action. I check the HTTP Headers to ensure that the data is being sent and it is so, where am I going wrong and how can I fix it.(Is there a better approach to this)
Script:
$(document).ready (function (){
$("form").submit (function (e) {
e.preventDefault();
$.post("/save",$(this).serialize(),function (data){
alert(data);
});
});
});
Action
public static Result save()
{
JsonNode json = request().body().asJson();
if (json == null)
return ok("expected json");
else
{
String value = json.findPath("video").getTextValue();
if (value == null)
return ok("did not find");
else
return ok(value) ;
}
}
routes
POST /save controllers.Application.save()
Upvotes: 1
Views: 216
Reputation: 55798
Both: Julien Lafont and dfsq are right, first: you are not serializing your form to JSON, second, as Julien stated, you don't need to... Using your current JS you can just use DynamicForm
in your save
action:
public static Result save() {
DynamicForm df = form().bindFromRequest();
String value = df.get("video");
if (value == null || value.trim().equals(""))
return badRequest("Video param was not sent");
// do something with the value
return ok(value);
}
BTW, don't use ok()
for returning responses for wrong requests. You have many options: badRequest()
, notFound()
, TODO
, and wild bunch of other Results, even raw: status(int)
, so you can read the status in jQuery without passing any additional reasons of fail.
If you really, really need to serialize form to JSON for any reason, let me know, I'll send you a sample.
Upvotes: 2