user1816744
user1816744

Reputation: 21

Posting JSON with AJAX request in play2

i'm using play framework 2.0.4

i have a route :

POST /addMail controllers.Application.addMail()

In my controller Application i define the addMail method :

public static Result addMail()
{
    JsonNode json = request().body().asJson();
    Long id = json.findPath("id").asLong(0);
    String email = json.findPath("email").getTextValue();
    GameScore gs = GameScore.findById(id);
    gs.setEmail(email);
    gs.save();
    return ok();
}

If i call this method through CURL i have no problem :

curl --header "Content-type: application/json" --request POST --data '{"id": 13, "email": "[email protected]"}' http://localhost:9000/addMail

But if i call this method through an AJX request i have a 500 response.

$addMailBtn.click(function(event) { 
        $this = $(this);
                var id = $this.attr("id").substring(14);
        var email = $("#saisieMailField_" + id).val();
        $.ajax({
                type: 'POST',
                url: "@routes.Application.addMail()",
        dataType:"json",
        data: {"id":id, "email": '"' + email + '"'},
                success: location.reload()
        })
    } );

If i print in my console my json data, json data is null when i perform my ajax request but is alright through curl.

I have tried to add @BodyParser.Of(play.mvc.BodyParser.Json.class) on my method but it doesn't change anything.

Thanks for your time.

Upvotes: 2

Views: 914

Answers (1)

col
col

Reputation: 397

This works for me. Note that i stringify the JSON object, and I think this is your problem.

$.ajax({
        type: "POST",
        url: "http://myservice:9000/api/v1/positions",        
        data: JSON.stringify({"nwLng":72.22,"nwLat":22.22, "seLng":22.22,"seLat":55.33}),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) { alert(data); },
        failure: function (errMsg) { alert(errMsg); }
    }); 

Upvotes: 1

Related Questions