Passing ruby variable via remote_function (JavaScript)

Hi,

Brand new to this so please excuse anything obvious that I don’t yet
get.

Here’s what I’m trying to do (This is all in a .rhtml file):

As a simple test I create a local variable called ‘localVariable’ and
give it the string “Hello” like this;

<% $localVariable = ‘Hello’ %>

Next I want to call a function (nameOfAction) which is expecting to
receive as input a variable (InputVariable). Now, this all works if I
hard code in a string in place of $localVariable, but I don’t want to do
that. The variable is being sent as the name of the variable and not its
contents. Do I need to escape something???

<% remote_function(:update => :name_of_div,
:url => { :controller => ‘nameOfController’,
:action => :nameOfAction },
:with => “‘InputVariable=’ + $localVariable”) %>

My question is, how do I get the $localVariable to convert to its
content within the above?

Thanks for any help.

Try this

<% remote_function(:update => :name_of_div,
:url => { :controller => ‘nameOfController’,
:action => :nameOfAction },
:with => “‘InputVariable=’ + #{$localVariable}”) %>

Thank you Anatol for your suggestion, but in this case it still did not
work.

After getting some sleep I have managed to fix my problem, I did it like
this;

<% remote_function(:update => :name_of_div,
:url => { :controller => ‘nameOfController’,
:action => :nameOfAction },
:with => “'InputVariable=” + $localVariable + “’”) %>

It’s all about the arrangement of double and single quotes.

A couple of comments,

a) I am aware that adding $ in front of a variable name makes it global
and not local as stated.

b) If any beginners (like me) are wondering how I got the
remote_function to work within a .rhtml file, the solution is to wrap it
in a javascript tag;

<%= javascript_tag(remote_function(:upda…and so on)) %>

Rich Johns wrote:

<% remote_function(:update => :name_of_div,
:url => { :controller => ‘nameOfController’,
:action => :nameOfAction },
:with => “'InputVariable=” + $localVariable + “’”) %>

This should also work…

:with => “‘InputVariable = #{$localVariable}’”

or

:with => %Q{ ‘InputVariable = #{$localVariable}’ }

_Kevin

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs