2

I am trying to submit a form as a JSON object because I want to create a REST API with play.

The issue that I have is that Play tells me that is not a valid JSON.

My FORM code:

@(form : Form[Product]) @main("Create Form"){
@helper.form(routes.Products.createProduct, 'enctype -> "application/json"){
    @helper.inputText(form("name"))
    <button>Commit</button>
} }

Controller Code:

// Read JSON an tell if it has a name Path
@BodyParser.Of(BodyParser.TolerantJson.class)
public static Result createProduct() {
    JsonNode json = request().body().asJson();
    String name = json.findPath("name").textValue();
    if (name == null) {
        return badRequest("Not JSON");
    } else {
        return ok(name);
    }
}

Whats the best way to do this? a read about submitting with Ajax but because I am new with play I don´t figure it out the way to do this with Play´s form syntax.

Aleyango
  • 323
  • 4
  • 14

1 Answers1

1

You can do it easily with jQuery (so make sure you have jQuery included in your head) and formAsJson() function based on serializeObject function.

@helper.form(routes.Products.createProduct(), 'id -> "myform") {
    @helper.inputText(jsonForm("name"))
    <button>Commit</button>
}

<script>
    $.fn.formAsJson = function(){
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return JSON.stringify(o)
    };

    var $myform = $("#myform");
    $myform.on('submit', function () {
        $.ajax({
            url: $myform.attr('action'),
            type: $myform.attr('method'),
            contentType: "application/json",
            data: $myform.formAsJson(),
            success:function(){
                alert("Great! Everything's OK!");
            },
            error: function(){
                alert("Booo, something wrong :(");
            }

        });
        return false;
    });
</script>

and your createProduct() action could look just like:

public static Result createProduct() {
    JsonNode json = request().body().asJson();
    String name = json.findPath("name").textValue();
    if (json==null || name==null || ("").equals(name.trim())){
        return badRequest();
    }

    return ok();
}
Community
  • 1
  • 1
biesior
  • 55,576
  • 10
  • 125
  • 182
  • thanks for your response, worked for me. But i figured our that is possible to identify the request type, because Play Framework has a MimeType Class. Do you know the way to create a switch clause in java to tell Play ok if MimeType.Json do this if is MimeType.HTML do another? – Aleyango Apr 17 '15 at 20:37