Documentation

You are viewing the documentation for Play 1. The documentation for Play 2 is here.

Ajax in the Play framework

The Play framework allows you to easily perform Ajax requests, and is shipped with jQuery by default. This section describes how to effectively use jQuery within the framework.

The Play framework also comes with the handy jsAction tag to transparently get a method definition from the controller.

Using jQuery with the jsAction tag

The #{jsAction /} tag returns a JavaScript function which constructs a URL based on a server action and free variables. It does not perform an AJAX request; these have to be done by hand using the returned URL.

Let’s see an example:

GET     /hotels/list        Hotels.list

Now you can import this route client side:

<script type="text/javascript">
   var listAction = #{jsAction @list(':search', ':size', ':page') /}
   $('#result').load(
       listAction({search: 'x', size: '10', page: '1'}), 
       function() {
           $('#content').css('visibility', 'visible')
       }
   )
</script>

In this example we are requesting the list method from the default Application controller. We are also passing three parameters: search, size and page. The request we perform is then saved into the listAction variable. Now using jQuery and the load function we are performing a request (an HTTP GET request in fact).

In fact, the following request is sent:

GET /hotels/list?search=x&size=10&page=1

In that case the request returns HTML data.

However, it is also possible to return JSON or XML and to have jQuery interpret the data. In your controller, use the appropriate render method (renderJSON, renderXML or an XML template).

Please refer to the jQuery documentation for more info.

Also please note that we could perform a POST; the jQuery method should then be changed to:

$.post(listAction(), function(data) {
  $('#result').html(data);
});

Using jQuery with the jsRoute tag

To have more control on the generated route, you also have the jsRoute tag, which is similar to the #{jsAction /} tag but it returns an object containing both the function which consctructs the URL based on the server action, and the corresponding HTTP method (GET, POST, etc.).

Example:

PUT     /users/{id}        Users.update

Then, in a template:

<script type="text/javascript">
    var updateUserRoute = #{jsRoute @Users.update(':id') /}
    $.ajax({
      url: updateUserRoute.url({id: userId}),
      type: updateUserRoute.method,
      data: 'user.name=Guillaume'
    });
</script>

With this approach, you won’t have to update your templates in case you decide to change the HTTP method in the routes file.

Continuing the discussion

Handle Internationalization.