# Ruby variable to JS in controller

**URL:** <https://www.ruby-forum.com/t/ruby-variable-to-js-in-controller/82823>\
**Category:** Rails\
**Created:** [January 21, 2007, 2:41pm UTC](https://www.ruby-forum.com/t/ruby-variable-to-js-in-controller/82823 "2007-01-21T14:41:26Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mravo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e495f1/32.png) [@mravo](https://www.ruby-forum.com/u/mravo)\
**Post date:** [January 21, 2007, 2:41pm UTC](https://www.ruby-forum.com/t/ruby-variable-to-js-in-controller/82823/1 "2007-01-21T14:41:26Z")

</div>

Hi,  
this is all new to me, so please don’t get upset if my questions are  
very obvious. I’m trying to display a ruby variable through JS alert  
function in the controller. Hope it makes sense, here’s my example:

myController.rb  
class …blah… \< ApplicationCon…blah…  
def someAction  
@myRvariable = “lala”  
render :text =\> “alert(\<%=@myRvariable%\>)”,  
:content\_type =\> “text/javascript”  
end  
end

myIndex.rhtml

\<%= link\_to\_remote "Display Rvariable", :url =\> {:action =\> "someAction"} %\>

So, I want to see an alertbox with “lala” when I click the link.  
Thank you very much!

---

<div class="post-metadata">

**Author:** ![mravo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e495f1/32.png) [@mravo](https://www.ruby-forum.com/u/mravo)\
**Post date:** [January 21, 2007, 3:06pm UTC](https://www.ruby-forum.com/t/ruby-variable-to-js-in-controller/82823/2 "2007-01-21T15:06:25Z")

</div>

Okey, nevermind that last post, I’ve found a solution. It’s like this;

class …blah…  
def someAction  
@myRvariable = “lala”  
render :update do |page|  
page.alert @myRvariable  
end  
end  
end

I would be really grateful for explanation of this, I still don’t know  
why it works, and why the previous doesn’t.  
Thanks!

---

<div class="post-metadata">

**Author:** ![mravo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/e495f1/32.png) [@mravo](https://www.ruby-forum.com/u/mravo)\
**Post date:** [January 21, 2007, 5:34pm UTC](https://www.ruby-forum.com/t/ruby-variable-to-js-in-controller/82823/3 "2007-01-21T17:34:19Z")

</div>

Hi Ma Mr,

Ma Mr wrote:

> I would be really grateful for explanation of this,  
> I still don’t know why it works, and why the  
> previous doesn’t.

The short answer is that the element (created by link\_to\_remote) that  
submitted the request to the server told the server via the message type  
(XMLHttpRequest) that the browser expected JS, not HTML, returned. Your  
first attempt used render which returned just the HTML you wanted  
displayed.  
Your second returned the HTML along with the JS to display it.

hth,  
Bill
