Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send Post Json with ajax and Play Framework 2

I have a problem regarding sending a json data to Play Controller.

seach.scala.html

$.ajax({
            type :  "POST",
            dataType: 'json',
            data: {
                'filter': "John Portella"
            },
            url  :  "@routes.Search.findPag()",
            success: function(data){
                console.log(data);
            }
        });
        return false;

Controller : POST /find/findPag Search.findPag()

public static Result findPag(){    
   JsonNode json = request().body().asJson();
   return ok();
}

Debugging I get json = null . Which you think may be the problem?. Thank.

like image 795
JohnPortella Avatar asked Dec 26 '22 04:12

JohnPortella


2 Answers

You'll have to stringify the data. As it is right now I think that .toString() will be called on the data object and that is not something that can be correctly parsed as JSON on the server side.

var d = { 'filter': "John Portella" };
$.ajax({
    type :  "POST",
    dataType: 'json',
    data: JSON.stringify(d),
    url  :  "@routes.Search.findPag()",
        success: function(data){
            console.log(data);
        }
});
like image 169
maba Avatar answered Jan 05 '23 13:01

maba


You'll have to "contentType" the data.

 var d = { 'filter': "John Portella" };
 $.ajax({
    type :  "POST",
    dataType: 'json',
    data: JSON.stringify(d),
    contentType: "application/json; charset=utf-8",
    url  :  "@routes.Search.findPag()",
    success: function(data){
        console.log(data);
    }
 });
like image 41
Nguyễn Văn Đức Avatar answered Jan 05 '23 14:01

Nguyễn Văn Đức