views:

92

answers:

1

I'm trying to come closer to a solution for the problem of my previous question.

The scheme I would like to try is following:

  1. User requests an action from RoR controller.
  2. Action makes some database queries, makes some calculations, sets some session variable(s) and returns some RJS code as the response. This code could either
    • update a progress bar and make another ajax request.
    • display the final result (e.g. a chart grahic) if all the processing is finished
  3. The browser evaluates the javascript representation of the RJS. It may make another (recursive? Is recursion allowed at all?) request, or just display the result for the user.

So, my question this time is: how can I embed a XMLHttpRequest call into rjs code properly?

Some things I'd like to know are:

Should I create a new thread to avoid stack overflow. What rails helpers (if any) should I use?

Have anybody ever done something similar before on Rails or with other frameworks?

Is my idea sane?

A: 

You may find RJS information harder to come by these days, I think unobtrusive JavaScript has gained more mindshare in the Rails community. What you're describing is certainly possible. My suggestion is to spend a little time learning AJAX with jQuery. Here are some steps you might take: 1) make a GET request to controller action, 2) do something, respond with JSON, 3) in your success handler code client side, determine if you need to call the server again.

Check the Railscast on jQuery, here is the transcription http://asciicasts.com/episodes/136-jquery

jQuery $.get() or $.getJSON http://api.jquery.com/jQuery.get/

Rails' respond_to block, check out the "wants.js" code here http://www.mckinneystation.com/2009/07/13/rails-respond_to-made-it-too-easy/

You could respond with your Ruby object serialized as JSON: render :json => @thing.to_json

Using $.getJSON() will deserialize the response into a JavaScript object, so you easily access properties with the dot syntax. e.g. (pseudo-code): $.getJSON('/url-to-thing.js', function(thing) { if( thing.status != 'done' ) { /* call function again */ } });

In this way, the function would stop being called once the 'thing' is 'done.' Getting comfortable with the responsibilities of the client and server parts can be daunting initially but will pay off in the long run by allowing you to develop far more dynamic and interactive web applications.

Andy Atkinson