10

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.

9
  • Try $('#trackers_count').data('trackers-count'), hyphen instead of underscore, as in the HTML. Commented Mar 5, 2015 at 5:26
  • @Santhosh, no change.. Commented Mar 5, 2015 at 5:29
  • Can you link to the specific rails cast you're talking about? Commented Mar 5, 2015 at 5:32
  • @patrick, I linked it up top. You only have to go as far as about the 4min mark before he starts talking about the gon gem and switches gears a little bit. Commented Mar 5, 2015 at 5:34
  • Can you put something inside the content_tag block like 'Loading tracker...'? Just to get it as per the railscast Commented Mar 5, 2015 at 5:37

4 Answers 4

12

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))
Sign up to request clarification or add additional context in comments.

4 Comments

Since I'm trying to pull in trackers which, in the controller, is @trackers =current_user.trackers.where(viewed: false).count and is based off the current user, how would you pull that in? Both of those methods above work for User.count but I'm not seeing how to implement it for the controller method.
I not got your question but it can work fine for controller variable like my_var = <%= @,y_controller_var %>. If controller variable is changing the state (I mean count or any other property of variable) you need to fire ajax request on some event or after each n seconds to ask server hey dude what is updated version of variable. Note that rails render a view(along with js) and forgets everything.
You can not use controller method here in place of User.count. You need to collect it in instance variable and you can use that variable here. Let me know what exactly you requirement is. There could be more better way to do this.
I may just have to send a get request to pull the data. I was just trying to populate the variable because I already have a get request method set up and all this needs to do is update the count the first time. After that, the rest of the method will take care of itself. There's got to be a way to get this info in there though. This shouldn't be this difficult
3

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

1 Comment

I had the document ready in my local code. Also gon gem seems to be running into the same issues with current_user not being able to be passed. I had tried that as well.
0

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!

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.