Reputation: 3988
I've got a ruby function creating an instance variable of a hash and i'm having trouble accesing it's values inside javascript.
this is my controller:
class TransferController < ApplicationController
def index
require 'json'
#@transfers = Transfer.select("transfer_id,section_id,sum(net) as net").group("transfer_id,section_id").having("sum(net) <> ?",0).order("transfer_id ASC")
@transfers = Transfer.select("section_id,section_name,sum(net) as net").group("section_id,section_name").order("section_id ASC")
h = Hash.new()
a = []
@transfers.each do |section|
h["name"] = section.section_name
h["size"] = section.net
a.insert(h)
end
@sectionhash = Hash.new()
@sectionhash["name"] = "stringush"
@sectionhash["children"] = a
end
end
and this is my view:
<h1><%= @sectionhash["name"] %></h1>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript">
var x = <%= @sectionhash["name"] %>;
alert(x);
</script>
The reuslt i get is that the shows me the value inside of the hash but the javascript does nothing. i even tried putting an alert before the assignment of the ruby code and it worked. so it's failing at the line with the embedded ruby. I've seen people answer in this forum that the embedded line i wrote is legal. Any ideas why this isn't working?
Upvotes: 0
Views: 128
Reputation: 3820
You still need to comply with normal Javascript synax rules.
var x = <%= @sectionhash["name"] %>;
will print: var x = stringush;
which is invalid due to no variable called stringush. You need to quote the JS string like so:
var x = '<%= @sectionhash["name"] %>';
This will print: var x = 'stringush';
which is what you want.
Upvotes: 5
Reputation: 2294
I think what you're looking for is for x
to be the string "stringush"
. For that, change your javascript to:
<script type="text/javascript">
var x = '<%= @sectionhash["name"] %>';
alert(x);
</script>
You need to quotes in there or the javascript will be var x = stringush;
and since there's no variable called stringush
, x will be undefined.
Upvotes: 2