Connecting Tech Pros Worldwide Forums | Help | Site Map

Embbeded Ruby (erb) from Javascript

Newbie
 
Join Date: Apr 2006
Posts: 3
#1: May 11 '06
I am wondering if it is possible to set embedded ruby variables in javascript. I've tried but to no avail. I'm thinking the javascript block won't recognize the <% %> erb tags.

What I want to do is basically call a javascript function from an onclick="setField('first_name')"

function setField(name)
{
<% fieldName = name %>
}

I don't think it's possible, because you are trying to put a javascript variable (name) into ruby, which I don't think it likes. Is there any possible way to do this. Or a confirmation that this cannot be done would be reassuring.

Thanks in advance

Banfa's Avatar
AdministratorVoR
 
Join Date: Feb 2006
Location: South West UK
Posts: 6,185
#2: May 11 '06

re: Embbeded Ruby (erb) from Javascript


I would say (remembering that until I saw this post I thought Ruby was and W3C DTD for adding text along side main text to indicate pronouciation, which is is see here) looking that this code that you Ruby code is running as server side script (most <% %> scripts run server side) and that the Javascript is probably (in the absence of anything indicating otherwise) running client side.

This means your Ruby script will have been executed before the Javascript has even been downloaded to the client.

Additionally as you posulate it is very unlikely that Ruby would be able to deal with a variable name from Javascript the reverse of this can be done though (set a javascript variable to the value of a Ruby variable, I am going to give a PHP example since I know PHP and not Ruby
[php]
function PrintSomething()
{
var ThingToPrint;

ThingToPrint = "<?php print( $PhpVariable ); ?>";

writeln( ThingToPrint );
}
[/php]

Since the php runs server side the short php script is replace by its output which is the value of $PhpVariable. When it gets to the client the javascript runs and picks up this value.

HTH
Reply