Friday, May 10, 2024
27
rated 0 times [  28] [ 1]  / answers: 1 / hits: 25197  / 13 Years ago, mon, may 9, 2011, 12:00:00

I am trying to use insert an Javascript variable in the <%= %> tags but it prints the variable name verbose. Here is my code



<script>
function getGraph(agency,device_id)
{
var i = document.createElement('img');
i.src = '<%= show_graph_hcfcd_url('device_id') %>';
$(graphDiv).appendChild(i);
}
</script>


Now the Problem is URL gets generated just fine except instead of value of device_id, 'device_id' appears in the rest url.



Any clues how to get over this?


More From » ruby-on-rails

 Answers
15

<%= %> will interpret the code on the server



and javascript variable is available to change on the client. So doing



<%= show_graph_hcfcd_url('device_id') %>


is probably not be the correct way of doing this.



You might want to try to put the url(s) in the data attibute of the element:



<div id=device_id data-url=<%= show_graph_hcfcd_url(@device.id) %>>...</div>

<script>
function getGraph(agency,device_id)
{
var i = document.createElement('img');
i.src = $(device_id).data(url);
$(graphDiv).appendChild(i);
}
</script>


also see



http://railscasts.com/episodes/324-passing-data-to-javascript



There's a good gem to do this called gon


[#92326] Saturday, May 7, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
melindab

Total Points: 511
Total Questions: 109
Total Answers: 106

Location: San Marino
Member since Thu, Jun 25, 2020
4 Years ago
;