I am trying to implement a progress bar (Javascript) with Ruby on Rails application, but I am having trouble passing values from controller to JS to update the bar.
Initially, I tried using a simple global variable ($count) but once loaded, the variable is always the same. It's not updated in the side of JS.
EDIT:
Now I am using gon gem to pass the value. But I only get the first value (that was setted when controller starts). When I call a method triggered by a button click, the value is updated but gon variable is always the same. Maybe is an error in rails/controller?
I saw an example with a method to expose variable to gon but is not working.
Note: If I remove the initialization before the search if, when search is clicked JS side shows "gon variable undefined"
Example Code: application_controller.rb
def application
@count =0 #gon assumes only this value
exposeUnProcessedJobToJavascript
if params[:search]
while(@count < 10)
exposeUnProcessedJobToJavascript
sleep 3
@count +=1
end
end
def exposeUnProcessedJobToJavascript
gon.watch.job = @count
end
end
application.js.erb
function addJobWatchers() {
if (gon.job != undefined) {
gon.watch('job', {
interval: 1000
}, updateProcessingJob);
}
}
function updateProcessingJob(job) {
if (job) {
console.log("JOB: " + job);
}
}
$(document).on('page:change', function() {
$("#search_button").click(function() {
console.log("click search");
if (typeof gon !== 'undefined') {
addJobWatchers();
}
});});
3 Answers 3
Here is a gem that can help you do just that. It has plenty of explanation and examples to get you started.
4 Comments
I believe this link will do what you are looking for. You shouldn't need the Gon gem. You should only need to do '<%= var %>'
http://railscasts.com/episodes/324-passing-data-to-javascript?view=asciicast
<%= javascript_tag do %>
window.productsURL = '<%= j products_url %>';
window.products = <%= raw Product.limit(10).to_json %>
<% end %>
Not Best Practice Way:
Since you already have the @count globally in your template. Set it to a data attribute. Then in your javascript, grab that data attribute. But this is an anti-pattern.
1 Comment
The problem seems to be related with the class. When Ajax try to access method inside class controller, it is instantiated again cleaning all variables. I solved the problem using Rails.cache.write(:count,0) and Rails.cache.read(:count) to render the value. Tip: Doesnt work for multiusers. Rails cache is shared between sessions.
Comments
Explore related questions
See similar questions with these tags.