Home > Blockchain >  Ruby on Rails : how to pass value to javascript
Ruby on Rails : how to pass value to javascript

Time:05-04

I want to pass the value from <%= controller.controller_name %> <%= controller.action_name %> to javascript as below

return (document.body.className  = " load-done 
            '<%= controller.controller_name %>' '<%= controller.action_name %>'
        ");

but it doesn't work, can anyone advise on this?

CodePudding user response:

The question is lacking information so I just guess you want to pass some data directly from the controller to your JS code. There are two "normal" ways to do this. The first is to do a direct call to the controller as a http call and return the response as a json. The second method is to pass the data as a class variable, then you can access it in the views folder from the html files. Here you can pass the variable to a div, span or whatever and access it in the JS by finding the html tag in the JS like so:

# controllers: 

def some_controller_method
  @temp = 'example data, could be any type'
end

# views
<%= content_tag :div, class: "some_class", data: {temp: @temp} do %>
<% end %>

# JS
$('.some_class').data('temp')
  • Related