Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4: Passing variables to javascript

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.

like image 521
Seph Cordovano Avatar asked Mar 05 '15 05:03

Seph Cordovano


1 Answers

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))
like image 132
Guru Avatar answered Oct 28 '22 03:10

Guru