0

I use the following JS code in my view to calculate two variables "user_name" and "user_uid":

<script type="text/javascript">
function f1() {
.
.
.
user_name = "some variable";
user_uid = "another variable";
});
}
</script>

I'd like to send the two variables "user_name" and "user_uid" to my controller. I use the following code:

<%= link_to "GO!", new_user_path(:userName => user_name, :userUid => user_id), :remote=> true %> 

My Controller and model work OK. But the two variables are not passed from the JS to the above embedded ruby code. I'd appreciate any pointers on what I'm doing wrong. Thanks!

0

1 Answer 1

6

Biggest mistake is not knowing where code is executed:

  • Code inside <%= ... %> (Erb markers) is executed on the server, before clients see any HTML.
  • JS is executed on the client, after being sent from a server.

There are a number of options, including creating the JS variable values using Ruby variables–whether that's the best option depends. For example:

function f1() {
  var user_name = "<%= escape_javascript(a_ruby_variable) %>";
  // Or, more concisely:
  var user_uid = "<%=j another_ruby_variable %>";

The Ruby variable could be initialized in the template, the controller, etc.

Again, whether it should be is debatable.

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

9 Comments

Thanks Dave! The two variables are created using FB API. They are created in JS. Do I have any other options? Thanks!!
@user1388066 That's a problem then; you'd need to build the link in a different way, or submit a form, or rewrite the link, or...
The link itself is working OK. If I set the variable within the link_to, it works fine. The variables are not being set the way I'd like to set them. And I'm not sure if that is even possible since my variables are set in JS. Thanks Dave!
If your controller MUST access this information then you will have to use an AJAX call. Transmitting to the info to your server, processing it, and returning an appropriate response. However, if you can, its much better to avoid doing this..
@user1388066 As I said, you need to build the link a different way--the link is useless by itself, it needs to be built to actually include the data you need. That's why I'm saying it needs to be built in a different way, because the server side doesn't have access to the client-side JS values.
|

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.