1

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!

2 Answers 2

5
<%= 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 ...

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @Anthony. That worked! What is the best resource to learn about passing params using forms? And why it is better? Thanks again!!
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
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.
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.