DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Frameworks
  4. jQuery AJAX With Play 2

jQuery AJAX With Play 2

Steve Chaloner user avatar by
Steve Chaloner
·
May. 08, 12 · Interview
Like (0)
Save
Tweet
Share
13.57K Views

Join the DZone community and get the full member experience.

Join For Free

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!

AJAX JQuery

Published at DZone with permission of Steve Chaloner, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Utilizing Database Hooks Like a Pro in Node.js
  • Securing Cloud-Native Applications: Tips and Tricks for Secure Modernization
  • 7 Ways for Better Collaboration Among Your Testers and Developers
  • Data Stream Using Apache Kafka and Camel Application

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: