Alex Klibisz
Machine learning research intern at ORNL.

Handling a JSON jQuery Ajax post in Play Framework 2.3.6

Alex Klibisz, 12/13/2014

I was having some trouble getting a result from my front-end jQuery ajax posts using a Play Framework 2.3.6 back-end (Java). I followed the Play Framework “Working with JSON” documentation, which provides the following example:

Back-end Java code to handle the Json post (function must be specified with a POST route in the routes file):

import com.fasterxml.jackson.databind.JsonNode;
import play.mvc.BodyParser;


@BodyParser.Of(BodyParser.Json.class)
public static Result sayHello() {
  JsonNode json = request().body().asJson();
  String name = json.findPath("name").textValue();
  if(name == null) {
    return badRequest("Missing parameter [name]");
  } else {
    return ok("Hello " + name);
  }
}

A JSON post made using the CURL command line tool:

curl
  --header "Content-type: application/json"
  --request POST
  --data '{"name": "Guillaume"}'

http://localhost:9000/sayHello

I got this sample working fine, but was still having trouble doing a standard jQuery Ajax post.

I ended up resolving two problems with my jQuery Ajax post:

  1. Play Framework requires the contentType header. Without that, you’ll be stuck with a null JsonNode object.
  2. Play Framework requires the JSON data being posted to be “stringify-ed”. Again, you’ll otherwise be stuck with a null JsonNode object.

So here is the same JSON Post, this time using the jQuery Ajax function. Notice the contentType and JSON.stringify(). Without those, you won't get very far.

$.ajax({
        type:  'POST',
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify('{"name": "Guillaume"}'),
        url: '/sayHello',
        success: function(json) {
            console.log('/sayHello POST was successful.');
            console.log(json);
        }
    });

Related Posts

Comments