Skizit
Skizit

Reputation: 44862

Play-Framework & Ajax how to?

I'm looking to do the following with AJAX...

I have a request to my server that takes a considerable amount of time to complete. The request is made in the controller and upon completion a HTML page is loaded informing the user of its completion.

However, what I'd like to do is have the request sent asynchronously, load the completion page and then load the requests result once it become available. I assume I would use AJAX to do this but I'm not exactly sure how. Can anyone point me to a good guide for doing something like this?

In case my explanation above is too confusing here is what I want to do...

1) Send request to server from Controller asyncronously.

2) load HTML page.

3) When request has completed fill field in already loaded HTML page with the response from the request.

Upvotes: 1

Views: 3581

Answers (2)

tmbrggmn
tmbrggmn

Reputation: 8830

There are 2 parts you need to take into account here:

  1. The client side
  2. The server side

For the client side; an Ajax request (for example, using jQuery.ajax) is per definition asynchronous. This means that you should be able to do the following - again using jQuery, which makes things easier - in your HTML page:

// The ready handler, which fires when the page has been loaded
$(function() {
    jQuery.ajax(
        // Do your thing here
    );
});

For the server side; in case your operation is going to be running for a relatively long time on the server (for instance several web service calls or long running IO operations) you'll want to use Play's asynchronous capabilities to let the Play! server execute things as effeciently as possible. It does this by offloading the long running operation(s) to their own threads.

The only thing left to do is set-up a route to your controller, implement the handler method and render something that your client-side JavaScript code is capable of parsing (JSON is probably the easiest, using Play's renderJson()).

I haven't used this set-up myself - maybe someone can confirm this would be the way to do it?

Upvotes: 0

James Ward
James Ward

Reputation: 29433

I wrote a tutorial recently that walks through how to do this with Play 1.2, JSON, and jQuery:
Tutorial: Play Framework, JPA, JSON, jQuery, & Heroku

Upvotes: 4

Related Questions