Implementing Polling For Rails Frontend To Call Update
I want to implement a system where my 'show' view, every 10 seconds will call update in the controller, then asynchronously updates the view without refreshing the page. I have it
Solution 1:
My solution would be this:
$.ajax({ method: "PUT", url: $(".some-element").data("url") })
.done(function(data) {
//here you can use the new data
});
Changes are that you have an element with class "some-element" with the attribute data-url set to the path that rails generate automatically for the update route. In your html you will have:
<divclass='some-element'data-url="<%= simulations_path(@simulation) %>">
...
</div>
In your controller you should return @simulation as json.
Other advantages of this solution is that you can avoid embedding ruby in javascript which implies that the server sends the file for every request.
The polling is right, but other ways to do it would be with web sockets. In Rails you have some gems to do that, and in the near future Rails 5 will come along with ActionCable. Anyway I would continue with polling since it is way simpler than websockets.
The way this solution works:
- You request the show view and the server responds with the html, js and css files.
- Polling starts and every 10 seconds a request is sent to simulations#update (simulations controller/update action).There you can update and save your simulation and return the new values.
- In jquery's ajax.done you get the new data and you can update the client side data.
Hope it helps,
Santiago
Post a Comment for "Implementing Polling For Rails Frontend To Call Update"