Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm using rails version 3.2.6 and I'm trying to pass a Javascript variable to another page "Test10". I have the following code in the view:

<script>
var message = "hello world!";
</script>

<%= link_to "Go!", Test10_path(), :with => "'message='+ message"  %>

The parameter is not passed to Test10. I have the following in the Test10 controller:

def Test10
  @hello = params[message]
end

Is this the right way to pass a Javascript variable to my rails controller? It is not working. I'd appreciate any pointers. Thanks!

share|improve this question

2 Answers 2

up vote 3 down vote accepted
<%= link_to "Go!", Test10_path(), :id => "my_link"  %>


<script>
    var message = 'test';
    var url = $('#my_link').attr('href') + '?message=' + message;
    $('#my_link').attr('href', url);
</script>

Something like this should work. Although most of the time, it's best to pass params by using forms instead ...

share|improve this answer
    
Thanks @Anthony. That worked! What is the best resource to learn about passing params using forms? And why it is better? Thanks again!! –  user1388066 Aug 1 '12 at 20:18
    
If you want to pass values from Javascript, just learn a little bit of jQuery. You also have to learn how to build forms with rails : guides.rubyonrails.org/form_helpers.html –  Anthony Alberto Aug 1 '12 at 20:20
    
Thanks @Anthony very much!! –  user1388066 Aug 1 '12 at 20:21
    
We went through the code and would like to mention that it's simply the submission of a GET request via the URL string. The URL string is plainly visible on the next page. Users who are more concerned about security should look elsewhere. +1 anyway for an obviously successful solution. –  La-comadreja Jul 18 at 12:50

You can't do this. JavaScript and Ruby code execute in completely different contexts, JavaScript on the client and Ruby on the server.

In general, if you want to communicate a value from the client to the server, you need to do so either by posting it back in a form or as part of a query string, or via AJAX.

In your specific example, you'll have to write some JavaScript which selects the anchor tag and appends the contents of the message variable to the anchor tag's query string. Something like the following:

<script>
  var message = "hello world!";

  // Select your anchor tag
  var link = $('a#my-link');

  // Append your message to the link's href attribute
  link.attr('href', link.attr('href') + "?message=" + message);
</script>
share|improve this answer
    
Thanks @meagar for your help! –  user1388066 Aug 1 '12 at 20:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.