Rails 4: Passing variables to javascript

23,746

Solution 1

I used to do:

var my_var = <%= User.count %>
console.log(my_var)

If it is an integer this works just fine. If, however, you want to pass objects, then use:

var my_var = JSON.parse(('<%= (@Users.count) == 0 ? "[]" : Users.first(10).to_json %>')

console.log(JSON.stringify(my_var))

Solution 2

You forgot about document ready. Try:

$(function(){ 
  var datadump = ($('#trackers').data('trackers'));
  console.log(datadump)
});

Or for provide data from Rails to JS use Gon gem https://github.com/gazay/gon

Share:
23,746
Seph Cordovano
Author by

Seph Cordovano

Updated on July 17, 2022

Comments

  • Seph Cordovano
    Seph Cordovano almost 2 years

    I've tried numerous methods and followed Ryan Bates' guide but no matter what I do I still get undefined.

    application.html.erb

    <body>
     <%= content_tag :div, id: 'trackers', data: {trackers: User.count} do %>
     <% end %>
    </body
    

    application.js.erb

    var datadump = ($('#trackers').data('trackers'))
    console.log(datadump)
    //returns undefined in console
    

    Viewing page source I can see the variable

    <div data-trackers="2" id="trackers">
    

    I'm passing User.count for now just to keep it simple but I'll need to be passing @trackers_count which is instantiated in a before_action in the application controller. I should be able to sort that out though once I figure out the problem here. Any suggestions?

    UPDATE - I've simplified all variables down to just trackers, instead of trackers_count to prevent any errors from syntax and updated code here to reflect that.

    ANSWER UPDATE - I selected the correct answer because if you want to pass any variables ASIDE FROM CURRENT_USER those methods worked perfectly. However, you can't access anything with current_user in JS because it loads before the window, so it can't know who the current_user is. It's a real pain but I just did it the long way and accessed the info I need through passing in json and an ajax requests.