Rails Ajax - Displays multiple responses in one action

I have an ajax request in my rails application that returns a variable from my controller action. Inside the controller action, I have a loop that may take some time to go through.

Controller

def myAction $j = 1 until $j > list_size do array << { :foo => $j } $j +=1; end @myvariable = array.to_json end 

myAction.js.erb

  var myVariable = JSON.parse("<%= escape_javascript(raw @myvariable) %>"); for (var k = 0; k < myVariable.length; k++) { $("#myDiv").append(myVariable[k].foo); } 

I want to be able to display the results at each step of the loop in the js.erb part, and not wait for the loop to complete. Is this possible without breaking the cycle and ending the action prematurely before the cycle ends? Maybe something like this (wrong pseudocode):

Controller

 def myAction $j = 1 until $j > list_size do array << { :foo => $j } render array.to_json $j +=1; end end 

myAction.js.erb

  var myVariable = JSON.parse("<%= escape_javascript(raw @myvariable) %>"); $("#myDiv").append(myVariable.foo); 
+7
javascript ajax ruby-on-rails
source share
2 answers

render stream: true will lazily load requests and allow them to run after assets and layout have been displayed. Streaming only works with templates, not with any other forms (e.g. json or xml).

So, you're out of luck, and you have to use ActionController::Live , which is available in Rail 4 and above. Live is a special module included in the ActionController class. It allows Rails to open and close the stream explicitly. Here is a pseudocode adapted to a more ruby ​​one and avoiding global variables:

 class MyController < ActionController::Base include ActionController::Live def action (1..list_size).each do |list_item| response.stream.write("{ "foo": #{list_item} }") end ensure response.stream.close end end 

The above code will loop from 1 to list_size and display each list_item immediately .

To use this, you must use Server-Sent Events. Usually the web page will have to ask if any updates are available. With events sent by the server, updates arrive automatically.

Please use the following resources to find out more aboue Streaming, SSE and Event Source:

+3
source share

This does not work if you have a synchronous connection. To deal with this problem, you need to use websockets. Websockets is an implementation of Javascript sockets that give you the ability to have a biliary connection to the client. That way, you can get the client to get some of the data when there is data, and so on.

There is a ruby ​​pearl called websocket-rails that implements websockets in rails. You can find it here:

https://github.com/websocket-rails/websocket-rails

This is the way I stood ...

0
source share

All Articles