0

How to pass ruby variable to JavaScript function. Here the ruby variable is an active record object.

= label = @label // active record object
- @x = 5

= javascript_tag "alert(#{ j(@x.to_json)});" // Working
= javascript_tag "proj.app.custom(#{ j(label.to_json)})" // Not working

proj.app.custom is a javascript function.

proj.app.custom = function(param) {
};

I am getting the following error

Uncaught SyntaxError: Invalid or unexpected token
9
  • 2
    What is label? Does label.inspect.to_s return something that looks like what proj.app.custom would accept? What is proj.app.custom and what parameters does it expect? Commented May 10, 2018 at 14:24
  • "How to pass ruby variable to JavaScript function" - you already know (your example with @x). Commented May 10, 2018 at 14:26
  • @spickermann - I have updated the js Commented May 10, 2018 at 14:29
  • What is the resulting rendered markup from the "not working" javascript_tag? Commented May 10, 2018 at 14:32
  • @SergioTulentsev - I can't understand ur question Commented May 10, 2018 at 14:34

2 Answers 2

1

Not sure what label contains, but if you want to pass a json you should not escape it:

= javascript_tag "proj.app.custom(#{label.to_json})" 
Sign up to request clarification or add additional context in comments.

Comments

0

Why not just do:

= javascript_tag "proj.app.custom(#{ j(@label.to_json)})"

I have a feeling that your assignment of = label = @label above isn't valid.

1 Comment

It looks weird, but it is valid :) It will just display the result of the assignment on the page.

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.