user3277633
user3277633

Reputation: 1923

Rails passing variable from View to Javascript file via HTML data tag

In my Tweets Controller, I have an array of tweets @tweets_array.

In my Tweets View/Show, I passed the value of @tweets_array to a data tag so that I can hopefully use the array in my javascript like so

<%= content_tag(:div, id: 'mycontainer', data: {source: @tweets_array})%>

In my javascript file, I want to set a variable var data to be @tweets_array so I can do some simply D3 visualization, so I call the following

var data = $('#mycontainer').data('source');

However, the above doesn't seem to work. I know that if i simply set var data = [1,2,3,4,5] then it works.

What is wrong with my way of retrieving the array from the view and passing it into the javascript?

This method is taken from this SO

Upvotes: 1

Views: 1729

Answers (3)

Kalman
Kalman

Reputation: 8131

The reason why what you have doesn't work is because content_tag helper expects the 2nd parameter to be the content of the tag (not attributes).

So,

<%= content_tag(:div, id: 'mycontainer', data: {source: @tweets_array})%>

won't work, but

<%= content_tag(:div, "", id: 'mycontainer', data: {source: @tweets_array})%>

will! See the difference?

Here is a very simple test to verify. View can be as simple as this:

<h1>Listing Tweets</h1>

<% @tweets_array = [1,2,3,4,5] %>
<%= content_tag(:div, "", id: 'mycontainer', data: {source: @tweets_array})%>

<button id="sourceBtn">Show source</button>

Then, in your application.js you can have the following:

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

$(function () {
  $('#sourceBtn').click(function(){
    var data = $('#mycontainer').data('source');
    alert(data);
  });
});

As you can see, when you click the button - you see the result

Upvotes: 2

csum
csum

Reputation: 2002

Your array needs to be written as json in the div:

<%= content_tag(:div, id: 'mycontainer', data: {source: @tweets_array.to_json})%>

Should produce the html:

<div id="mycontainer" data-source="[48.95, .......]"></div>

Now javascript can parse the attribute:

var data = JSON.parse($("#mycontainer").data('source'));

You may also need to use raw or html_safe when printing the json on the rails side.

Upvotes: 3

hamitron
hamitron

Reputation: 219

I usually dislike having to add a new gem everytime as a solution, but Gon has has been instrumental in all of my d3 work within rails.

You set your variables in your controller as gon.variable_name = variable_value

And retrieve them in your javascript as gon.variable_name

Upvotes: 2

Related Questions