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?
<%= %>
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"
Here is how i have solved this for now:
<script>
function getGraph(agency,device_id)
{
var i = document.createElement('img');
var url = '<%= show_graph_hcfcd_url('device_id') %>'; //new change
url = url.replace('device_id',""+(device_id*1000)); //new change
i.src = url;
$(graphDiv).innerHTML = "";
$(graphDiv).appendChild(i);
}
</script>
The lines in the bold show what i did. Basically replaced the "device_id" in the url with its value.
But I am still hoping for a more elegant solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With