Tag Archives: json

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

backbone.js – M without the VC

I’ve recently been doing a lot of work with backbone.js, a JavaScript MVC framework that’s excellent for building clean applications that are backed by RESTful JSON web services. It offers a nice separation of concerns, supports your favourite JavaScript templating engine and is well-documented. What else could you need?

Well, sometimes the answer is a little bit less than what’s on offer. What about cases where you want to use just part of the framework? That’s also possible – in this case, I’m going to demonstrate how you can use backbone models to interact with your server-side code, but without the associated views and controllers.

Backbone models extend the framework’s Model class, and so you can get RESTful behaviour for free. On the server side (which, unsurprisingly, I’m using the Play! framework for), we have a couple of models:

@Entity
public class User extends Model
{
    public String userName;
    
    public String displayName;
    
    public String fullName;
    
    @OneToMany(cascade = CascadeType.ALL)
    public List friends;

    public static User findByUserName(String userName)
    {
        return find("byUserName", userName).first();
    }

    // builder methods not shown
}
@Entity
public class Friend extends Model
{
    @OneToOne(optional = false)
    public User user;
    
    public Friend(User user)
    {
        this.user = user;
    }
}

The User class is only going to be used on the server side, but Friends will be retrieved using a RESTful service that returns JSON.

window.Friend = Backbone.Model.extend
  ({
    urlRoot: "http://localhost:9000/api/friends",
    defaults: {
      "id": null,
      "user": null
    }
  });

window.FriendCollection = Backbone.Collection.extend
  ({
    model: Friend,
    url: "http://localhost:9000/api/friends"
  });

Once client-side instances of Friend are created, calling methods such as fetch() will result in a RESTful call based on the URL given in the model declaration. To integrate this with the server side, we add entries to the routes file. In this case, we’re only going to GET all the friends of the current user, but the same principle applies to other HTTP methods such as PUT and DELETE.

GET     /api/friends                            Friends.all

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

public class Friends extends Controller
{
    public static void all()
    {
        User user = User.findByUserName(session.get("userName"));
        renderJSON(user.friends);
    }
}

At this point, we now have everything in place to make RESTful calls and react to the asynchronous results.

<script type="text/javascript">
    function showFriends() {
        var friends = new FriendCollection();
        // Retrieve the data from the server, do something with it on a successful return
        friends.fetch({
            success: function() {
                // do something with the result.  All friends in the collection can be accessed by iterating over (or directly accessing) friends.models 
            }
        });
    }
</script>

Who are my <a href="javascript:showFriends()">friends</a>?

In just a few lines of code, you have smooth, clean access to your web services and a declarative model that can easily be kept in sync with your server-side models.

A complete working example can be found here. Unzip it, cd into the bbm directory, type “play run” and point your browser at http://localhost:9000.

EDIT: Please note this is written using Play 1.x. I guess I need to get in the habit of clarifying which version of Play I’m using now that Play 2.0 is nearly ready!

EDIT 2: Just to keep things even, here’s an simplified implementation in Play 2.