Felix
Felix

Reputation: 694

Respond multiple times to one request?

One place in my rails app requires loading a number of responses from an external server, which currently looks like this:

  1. User makes an AJAX request to the server. "Loading data..." is displayed.
  2. 5-30 seconds later, the rails app sends response (assuming the data has not been cached).

It would be much better if I could keep the user informed during that long waiting period with messages informing them of the progress of the request. Such as:

  1. User makes request (as before).
  2. Message "Retrieving ABC" displayed
  3. Message "Retrieving XYZ" displayed
  4. Message "Processing data" displayed
  5. Full response as normal.

How can I go about doing this? I don't think that sending back multiple JavaScript responses to one request is possible, but have no idea what the correct way of doing this is!

Upvotes: 0

Views: 1202

Answers (1)

Tigraine
Tigraine

Reputation: 23648

This is tricky but Rails supports the notion of streaming a request. But you probably have to do a lot of work in your project to make this work.

Tenderlove (Aaron Patterson) posted a intro into how Streaming works in Rails and I believe there is a Railscast on this topic.

Probably a simpler solution would be to split this into multiple requests. So the main request (assuming it's an ajax request) takes forever to complete. Meanwhile you poll the status on a different ajax request and the main action updates the database with it's process so the other request can retrieve that status and send back the appropriate response (where in the process the main request currently is)

So I'd assign each request something like a request id and then have a database table for those requests and their statuses (could be as simple as having only id:integer and status:string)

You assign the request id on the client (use some random data to create a hash or something) and start the long request with that Id. The client then polls another endpoint with that same id to get the status back.

The long running request in the meantime updates the Status table with the id it was given and where it is currently in processing that request.

Upvotes: 3

Related Questions