yerassyl
yerassyl

Reputation: 3057

How to access variable sent from Rails 4 controller in JavaScript?

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.

Upvotes: 0

Views: 59

Answers (1)

caspg
caspg

Reputation: 399

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

Upvotes: 1

Related Questions