bloomers
bloomers

Reputation: 275

How can I pass a ruby(rails) variable into Javascript?

This is an app in rails.

Here's what I have in 'routes':

 resources :destinations

Here is what I have in 'destinations_controller':

def show
     @destination = Destination.find(params[:id])
end

Here's what I have in 'views/destinations/show.html.erb':

<h2><%= @destination.latitude %></h2>

<script>

    var dest_lat = <%= @destination.latitude %>

</script>

Here's what I have in 'application.js':

var dest_location = {dest_lat};

This is the third time I've built this app. Initially, I get no errors and all the coding works fine... for a few hours. Then, without me changing anything, the value in @destination.latitude still appears in the h2 tag, but I start to receive the error:

Uncaught ReferenceError: dest_lat is not defined

with a link that shows its use in 'application.js', and the app ceases to work.

Why?

Any help is appreciated.

Upvotes: 3

Views: 3505

Answers (2)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33471

This isn't printing something useful for Javascript:

<script>
    var dest_lat = <%= @destination.latitude %>
</script>

Try instead to change it to:

<script>
    var dest_lat = '<%= @destination.latitude %>';
</script>

Here you can see that the quotes make the difference.

var dest_lat = some_value;

var dest_lat = 'some_value';
console.log(dest_lat);

Update: To make your data available in your application.js you can store them in a non-visible div, with content_tag, which will content your @destination.latitude and anything else you need to work

# your_view.html.erb
<%= content_tag :div, class: 'destination_latitude', data: {destination_latitude: @destination.latitude} do %>
<% end %>

Then you can access to them as a Javascript object:

document.addEventListener('DOMContentLoaded', function(e) {
  console.log($('.destination_latitude').data('destination-latitude'));
});

Upvotes: 5

Paul
Paul

Reputation: 36349

Check your rendered HTML output. As I said in my comment, I'm guessing that the script tag with the src pointing at your javascript file(s) is being called before the script tag with the embedded javascript. The fix is to just change the order that they're declared on the page, but the specifics will depend on how your layouts, pages, and partials are setup (which I can't tell from your posted question).

When all is said and done, you'll have something like:

<script type='text/javascript'>
  // Your embedded script
</script>
<script src='/path/to/application.js' type='text/javascript'></script>

in your rendered output.

Upvotes: 1

Related Questions