Seph Cordovano
Seph Cordovano

Reputation: 2054

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.

Upvotes: 10

Views: 26983

Answers (4)

Jose Paez
Jose Paez

Reputation: 847

This could help you.

For me, I wanted to turn this array

  @dates = ["2018-12-24", "2018-12-25", "2018-12-26", "2018-12-27", "2018-12-28"]

into a variable in Javascript. I tried the basic:

var dates = <%= @dates.join(", ") %>
alert(my_var)

This alerted this exact text:

1995

I have no clue why.

Since it wasn't working I tried Guru's solutions up there by copying and pasting, but it was worse now I had an error coming up in my code. Finally I got Guru's solution to work like this:

(the print embedded ruby open and close worked outside the JSON.parse() and there was a missing ")" )

  var dates = <%= JSON.parse(@dates.join(", ").to_json)%>
  alert(dates)

But even though it didn't crash, want to guess what it alerted?

Yeap, you guessed it:

1995

So I gave up and I used a work around:

In my view edit.html.erb

<div class="dates"><%= @dates.join(", ") %></div>
<script>
  var dates = $(".dates").text()
  alert(dates)
  $(".datepicker").val(dates)
</script>

That allowed me to feed the variable, therefore alert the correct data and set the Datepicker's input with the correct information. I'm still bugged for not being able to solve the hole 1995 problem. If someone could be so kind as to explain, I would really appreciate it. Hope this helps and have a great day!

Upvotes: 0

laaksom
laaksom

Reputation: 2210

Stumbled here from google. In my case, I was trying to pass an array of objects to a js.erb, which triggered an event a front end component listened to. For anyone from google, I solved this issue by doing the following:

In my controller.rb:

@payload = []

array.each do |a|
  temp = {
    foo: a.id,
    bar: a.relation.relation
  }
  @payload << temp
end

in my js.erb:

$(document).trigger('event', { data: <%= @payload.to_json.html_safe %> })

in my component.js:

$(document).on('event', (e, data) => {
  console.log(data) //should be array of objects in proper format
})

Hope this helps someone!

Upvotes: 0

Guru
Guru

Reputation: 1410

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))

Upvotes: 12

bondarenko.dev
bondarenko.dev

Reputation: 146

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

Upvotes: 3

Related Questions