0

I have a @coords variable:

#maps controller
 def index
    @coords = Map.all
  end

Inside index.html.erb, I have:

<%= content_tag 'div', id: 'coords', data: @coords.to_json do %>

<% end %>
 

How my content_tag looks like after rendering HTML page:

[{"id":1,"vibration_level":456,"lat":"71.45543","lon":"53.43424","time_sent":"1994-05-20T00:00:00.000Z","created_at":"2015-06-13T06:53:30.789Z","updated_at":"2015-06-13T06:53:30.789Z"} ]

How can I access it from a JavaScript file.

3
  • Are you rendering it as text in a div? You need to render it in a script tag and assign it to a variable. Then any JavaScript code on the page can reference that variable. Commented Jun 13, 2015 at 11:57
  • @David, I tried that too, the problem is that my external script is loaded first, so it cant see my variable defined in html page. Commented Jun 13, 2015 at 12:03
  • Then load the scripts in the correct order. No language can reference a value before it's been defined, this isn't specific to Rails and/or JS. Commented Jun 13, 2015 at 12:04

1 Answer 1

1

You should consider using gon gem. This gem is for sending data from rails to your JavaScript.

You can do smth like this:

#map controller    
def index
  @coords = Map.all
  gon.coords = @coords.to_json
end

And then you can acces your variable in JS: gon.coords

Sign up to request clarification or add additional context in comments.

2 Comments

Personally, I think this is much better than sending an instance variable's contents as a string into a data- tag in the view and then hacking away with jQuery to grab the string and then parsing it back into an object. On a side note, would you happen to know if gon can send over any kind of data type? Like a function?
github.com/gazay/gon/wiki/Usage-example You can for sure pass int, array, hash, string.

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.