Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use POST parameters in Play Framework?

I'm trying to make a POST request using JavaScript routing. In the routes file:

POST /comments controllers.Clients.addComment(text: String, client: Int)
GET /assets/javascripts/routes controllers.Application.javascriptRoutes()

on page:

jsRoutes.controllers.Clients.addComment(args.text, @client.id).ajax(...);

But it creates the request

POST http://localhost:9000/comments?text=qwe&client=1 HTTP/1.1

How do I make it pass parameters in the POST body instead of a request string?

like image 935
Poma Avatar asked Dec 19 '25 00:12

Poma


1 Answers

Tak a look at ajax() documentation - that is, such example:

$.ajax({
    type: "POST",
    url: "some.php",
    data: { name: "John", location: "Boston" }
});

As Play JavaScript route already defines url and request method (type), you need only to add data (of course you don't need to specify them as a params in brackets)

jsRoutes.controllers.Clients.addComment().ajax(
    data: {
      client: @client.id,
      text: args.text
    }
);

Also you can send a text only to given client (determined by the URL (it can be POST but PUT looks nicer :)):

PUT /comments/:client     controllers.Clients.addComment(client: Int)

in the view:

jsRoutes.controllers.Clients.addComment(@client.id).ajax(
    data: { text: args.text }
);

So it will perform PUT request to http://domain.tld/comments/123 and text will be available in the form() as it was sent with POST:

public static Result addComment(int client) {
    String receivedText = form().bindFromRequest().get("text");
    // save it to DB ...
    return ok( "Added comment: "+ receivedText+ ". for client id: " + client);
}
like image 84
biesior Avatar answered Dec 20 '25 18:12

biesior



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!