jQuery AJAX With Play 2
Join the DZone community and get the full member experience.
Join For FreeI’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!
Published at DZone with permission of Steve Chaloner, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments