Forum: Ruby on Rails pass json data into javascript

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
A07ecf0ebe864d1e339391da2c008008?d=identicon&s=25 Winter Sleep (wintersleep)
on 2008-11-21 00:47
Hello from a Ruby on Rails beginner!

I've been trying to pass some data to a variable in Javascript by using
json. Seems like the Javascript variable doesn't receive the data
correctly.

This is the code in controller. @courses variable find the data from
database.

class CoursesController < ApplicationController

  def index
    @courses = Course.find(:all)
    end
end

This is Javascript code in view.

<script type="text/javascript">
var markers=<%= @courses.to_json %>;
</script>

The following code show the data in browser with no problem. That means

<p><%= @courses.to_json %></p>

But the following code doesn't show data in browser right. The output is
a string of "undefined".

<script type="text/javascript">
var markers = <%= @courses.to_json %>;
for(i=0; i<markers.length; i++) {
document.write(markers[i].latitude, markers[i].longitude,
markers[i].name);
}
</script>

I don't know what goes wrong. Please help. Thank you in advance.
This topic is locked and can not be replied to.