1

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() 
4
  • 3
    Your are not sending JSON to the server. Commented Feb 10, 2013 at 20:04
  • 1
    You're sending classic form parameters, not Json. it's a Jquery problem, not related to playframework. Search "jquery serialize form as json" for more details. Or just handle form data in your controller. Commented Feb 10, 2013 at 20:27
  • @JulienLafont & dfsq - please, give an answer (not a comment) with sample of form serialization to JSON. Commented Feb 10, 2013 at 20:31
  • When typing the edit description I accidentally pressed enter instead of backspace, it should be 'retagged, changed java to JavaScript'. Perhaps you should read the tag wiki of JavaScript. Commented Feb 10, 2013 at 21:18

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.