0

Hi I want to create a page where it monitors(view) or render the value of the variable inside the controller dynamically as the iteration of variable goes by.

view.html.erb

<a id='get_value' class="btn">Run</a>
<ul id="value_variable_from_controller"><ul>

<script>
var getTheValue=function(){
      $.ajax({
        type:'GET',
        url:'/run/results',
        success:function(data,status){
        <!--how to dynamically UPDATE the value_variable_from_controller?-->
        alert("Successfully");
        }
      });
    }
    $(document).on("click","#get_value",getTheValue);
</script>

And here's my controller where i iterate the value of x,

results.rb

x=0
5.times do 
 x++
 sleep(1)
 #HOW TO RETURN THE VALUE OF VAR X EVERY UPDATE?
 #render :json => x, :status => :ok #do i need to have a loop in js?
end

Many Thanks.

1 Answer 1

1

If I understand you correctly you want to update the value in the HTML document every time it is updated on the server, correct? There are ways to accomplish this, although the transitioning of state between client and server is usually initiated by the client. 1

To combat this, websockets are currently the most popular approach - basically opening up a two-way communication pipe between the client and the server. Of course, for your simple example this might be overkill (unless you require heavy real-time interactions between the client and the server - then it's certainly worth taking a gander at) - and something like polling might be more suitable (which is indeed initiated by the client), although it will generate a large number of requests.

You might also consider long polling which only opens one connection.

Polling is a technique in which the client calls the server requesting data at a certain interval, which would work for your situation. From the code you posted it also seems like you want it to be possible to fetch the value by clicking on the #get_value link, which can utilise the same method as the long polling service. Here's an example:

// in your view/javascript
$(document).ready(function() {
  function getValue(trigger) { 
    $.ajax({
      type: 'GET',
      url: '/run/results/',
      success: function(data, status) {
        $('#value_variable_from_controller').text(data.x);
        if(trigger) { 
          setTimeout(getValue(true), 1000); }
      }
    )} // end AJAX
  } // end getValue

  // binding the action to your link as well
  $('#get_value').on('click', function(event) {
    event.preventDefault();
    getValue(false);
  });
  // start the polling
  getValue(true);
}); 

# in your controller
 @x = 0 # initial value
def results
  @x++ # increment every time this action is called
  render @x.to_json
end

This way the client initialises the data flow, and the server mutates state in response to a client request - which is the norm in a client/server architecture.

1 The client–server characteristic describes the relationship of cooperating programs in an application. The server component provides a function or service to one or many clients, which initiate requests for such services. (http://en.wikipedia.org/wiki/Client%E2%80%93server_model)

Sign up to request clarification or add additional context in comments.

4 Comments

Nice answer, thank you. it solves my problem, im still encountering some error but im working on it. thank you @nocohvi.
Anytime :-) If you have any questions don't hesitate to shoot some my way!
Hi nicohvi how about if the transitioning of state between client and server was initiated by the server/method in rails?
Then you would have to use websockets or server-sent events. This is not that commonplace in rails applications (and is quite complicated because it involves using another server to function as a websocket-server, as well as a key/data-store to store the connnected sockets), but if you want to do it that way then please have a look at this: github.com/websocket-rails/websocket-rails :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.