jQuery AJAX with Play 2

I’ve just prepared a course on jQuery to give to my colleagues, and one of the sections covers jQuery’s AJAX features. To demonstrate these, I wrote a quick web app using Play 2. Since there have been a few questions asked in various places on how this works, I’m going to break it down here with some simple examples of the main $.ajax() method, plus the shorthand methods that simplify its use.

$.ajax()

jQuery’s $.ajax() method is part of the low-level interface, and can be configured to provide all your AJAX needs. For this example, we’re going to do a simple GET that will result in a 200 response from the server, along with a text message.

The JavaScript:

$.ajax(ajaxParameters({
      url: '/ajax',
      success: function(data, textStatus, jqXHR) {
        window.alert(data);
      },
      error: function(jqXHR, textStatus, errorThrown) {
        window.alert(textStatus);
      }
    }));

Note the URL – this results in a call to http://localhost:9000/ajax, and so must appear in the routes file:

GET     /ajax                       controllers.Application.ajax()

The server-side implementation is about as simple as it gets:

public static Result ajax()
{
    return ok("Here's my server-side data");
}

Responding to errors

Take a look at the JavaScript again – you will see there are handlers declared for success and error conditions. What’s the difference? A 200 response will trigger the success handler, and other codes trigger the error handler. Let’s tweak the code to show this working.

The JavaScript. The only thing that has changed here is the URL – it now points to a URL that is guaranteed to return a non-200 response.

$.ajax(ajaxParameters({
      url: '/ajaxWithError',
      success: function(data, textStatus, jqXHR) {
        window.alert(data);
      },
      error: function(jqXHR, textStatus, errorThrown) {
        window.alert(textStatus);
      }
    }));

The route:

GET     /ajaxWithError              controllers.Application.ajaxWithError()

And the server-side implementation:

public static Result ajaxWithError()
{
    return badRequest("Somehow, somewhere, you screwed up");
}

And that’s it – you’re now handling success and error conditions.

Shorthand methods

jQuery usefully provides shorthand methods that simplify usage of $.ajax(), and in some cases provide additional functionality such as parsing repsonse data into JSON objects, or loading content into elements.

$.get()

$.get() is, unsurprisingly, for issuing asynchronous GETs to the server. You can provide parameters, and give a single function that will be executed if the call is successful.

The JavaScript:

$.get('/get',
      {'foo': 'bar'},
      function(data) {
          window.alert(data);
      });

The route – note this doesn’t specify a method parameter!

GET     /get                        controllers.Application.get()

The server-side implementation:

public static Result get()
{
    Map queryParameters = request().queryString();
    return ok(String.format("Here's my server-side data using $.get(), and you sent me [%s]",
                            queryParameters.get("foo")[0]));
}

Handling errors

In the real world, you will receive errors sometimes and the above JavaScript doesn’t handle this. The key is to use jQuery’s event-handling features instead of providing callbacks. In this example, any success, error and completion events fired by $.get() are handled.

$.get('/getWithError')
      .success(function(data) {
        window.alert('Success: ' + data);
      })
      .error(function(data) {
        window.alert('Error: ' + data.responseText);
      })
      .complete(function(data) {
        window.alert('The call is now complete');
      });

The route:

GET     /getWithError               controllers.Application.getWithError()

The server-side implementation:

public static Result getWithError()
{
    return badRequest("Something went very, very wrong");
}

$.post()

So far, so good, but what if you want to POST data to the server? You can use $.post() for this. Interestingly, there are no shorthand methods for DELETE, PUT, etc – you have to use the $.ajax() method for these.

The semantics are the same as for $.get(), so I’m not going to provide an event-driven here. This is using a regular callback.

The JavaScript:

$.post('/post',
      {'foo':'bar'},
      function(data) {
          window.alert(data);
      });

The route – note the POST HTTP method is used.

POST    /post                       controllers.Application.post()

And the server-side code:

public static Result post()
{
    Map parameters = request().body().asFormUrlEncoded();
    String message = parameters.get("foo")[0];

    return ok(message);
}

$.getJSON()

$.getJSON() loads JSON-encoded data from the server using a GET HTTP request (to steal a line from the jQuery docs). This means the data returned can be treated immediately as a JSON object without the need to process it further.

The JavaScript:

$.getJSON('/getJson',
          function(data) {
              // data is a JSON list, so we can iterate over it
              $.each(data, function(key, val) {
                  window.alert(key + ':' + val);
          });
       });

The route:

GET     /getJson                    controllers.Application.getJson()

Server-side code:

public static Result getJson()
{
    List data = Arrays.asList("foo", "bar");
    return ok(Json.toJson(data));
}

$.getScript()

$.getScript() loads a script from the server using a HTTP GET, and then executes it in the global context.

The JavaScript:

$.getScript('/getScript');

The route:

GET     /getScript                  controllers.Application.getScript()

Server-side code:

public static Result getScript()
{
    return ok("window.alert('hello');");
}

Handling events

This example couldn’t be simpler. It could, however, be slightly more complex. The events generated by $.getScript() are slightly different to the success, error, etc events of the other methods. For $.getScript(), there are done and fail events. For success, you have to use a callback.

$.getScript('/getScriptWithError',
            function() {
                window.alert('This is the success callback');
            })
            .done(function(script, textStatus) {
                window.alert('Done: ' + textStatus);
            })
            .fail(function(jqxhr, settings, exception) {
                window.alert('Fail: ' + exception);
            });

The route:

GET     /getScriptWithError         controllers.Application.getScriptWithError()

The server-side implementation. Note it’s returning a 200 response but with broken JavaScript.

public static Result getScriptWithError()
{
    return ok("this is not a valid script!");
}

.load

Last but not least is .load(). Note this isn’t $.load(), but rather $(a selector).load() as its purpose is to retrieve HTML from the server and place it into the matched element.

The JavaScript:

$('#loadContainer').load('/load');

The route:

GET     /load                       controllers.Application.load()

The server-side implementation:

public static Result load()
{
    return ok(snippet.render());
}

The template:

<div id="aTable">
    <table>
        <tr>
            <td>Foo</td>
            <td>Bar</td>
        </tr>
        <tr>
            <td>Hurdy</td>
            <td>Gurdy</td>
        </tr>
    </table>
</div>
<div id="aList">
    <ul>
        <li>Foo</li>
        <li>Bar</li>
    </ul>
</div>

Loading fragments

.load() can take a second parameter within the URL string, separated by a space. This parameter is a selector – if present, jQuery will extract the selected element from the HTML and insert only that into the target.

$('#loadFragmentContainer').load('/load #aList');

Note there is no change to the route, the server-side code or the template here – this is purely a client-side operation.

That’s all, folks

jQuery simplifies making AJAX calls, and Play simplifies receiving and responding to those calls. A perfect match!

An example implemtation of all these features is available here: jquery-ajax

Leave a comment ?

15 Comments.

  1. Well done, Thanks for your sharing

  2. Very nice, simple and to the point. Makes a good reference.

    If you feel like doing a websocket tutorial next, I would love to see how that works from end-to-end. By which I mean, I would love you to do the hard work and figure it out :grin:

  3. Oh yeah? What, you’re too lazy to work this stuff out and blog it for yourself?

    Wait, I forgot…you have – http://www.underflow.ca/blog/ :)

    My bad.

    There’s already a entry using websockets (http://www.objectify.be/wordpress/?p=341) but it essentially repurposes the existing chatroom example app.

    Websockets are on my todo pile, but if you’re interested I’l bump them up the list a bit.

  4. I’m sad. I was expecting more elaboration about Play 2, but what is used is as the minimum as possible, nothing more.

    You could have talked about how to know if the request come from ajax or not, how to make a json response from the server.

    It’s not “jQuery AJAX with Play 2″, it’s “jQuery Ajax with some backend”.

  5. The aim of the post was to show how to set up the routes and extract parameters from the AJAX requests. Using this information, you can immediately write an AJAX-based Play 2 app.

    Creating JSON responses, etc, is standard Play 2 and out of context here. If you want me to elaborate further on that, or other topics, then let me know.

  6. Haha, nice I got a plug!

    I also wanted to learn backbone.js so that solves two problems at once.

  7. Thanks, this is great :)

  8. This was awesome had trouble understanding ajax and jquery and you cleared that up!

  9. This is good — but I am really confused. What if I have a few places where I want to use “get” on my web page. How the frick do I route those? Doesn’t the router get confused by all the get’s?

  10. @Ted – each route is unique, so the URL of each GET just needs to conform to the route you want to access.

  11. This post help me a lot. Thanks!!!!

  12. Terrific no-fluff example. Thanx.

  13. It would be nice to see how to call a server function that takes some parameter as input

  14. Do you mean a POST, or a GET? There’s a POST example above.

    For a GET, the parameters form part of the URL, so given a route


    GET /get/:id controllers.Application.get(id: Long)

    the JavaScript would be


    var itemId = // get a value from somewhere
    $.get('/get/' + id)
    .success(function(data) {
    window.alert('Success: ' + data);
    })
    .error(function(data) {
    window.alert('Error: ' + data.responseText);
    })
    .complete(function(data) {
    window.alert('The call is now complete');
    });

    However, I think you would be better off using the JavaScript routing support of Play 2. You can find examples of this for
    Java: http://www.objectify.be/wordpress/?p=734
    Scala: http://www.objectify.be/wordpress/?p=746

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackbacks and Pingbacks: