Reputation: 2044
It seems a stupid question, but there are no way to achieve this
With Rails 4.2.5.
in a remote call to the controller,
def update
# ... save ...
@notice="S'han trovat errors"
# automatically renders update.js.erb
end
in update.js.erb
alert('<%=(@notice)%>');
What I've tried:
1)In the controller:
@notice="S'han trovat errors".html_safe
2)another proof, in js.erb:
alert('<%=raw(@notice)%>');
In both cases, when javascript function alert()
is executed, it hangs without any message in terminal neither in browser console ¿?
3)I have tried too:
alert('<%=escape_javascript(@notice)%>');
But doesn't work, shows "S'han trobat..."
Of course, if I show in index.html.erb
, @notice , the result is correct (S'han trobat..)
I don't know how to pass from controller to js.erb a " ' " character in a string instance variable to be shown
Thanks
Upvotes: -1
Views: 1459
Reputation: 4770
Use alert(<%= JSON.generate(ERB::Util::html_escape(@notice)) =>)
, which will work for all text, including with line breaks, prevent XSS, etc.
https://code.dblock.org/2024/10/30/safely-passing-ruby-variables-to-javascript-in-erb.html
Upvotes: 0
Reputation: 2044
The problem is that javascript recives:
alert('S'han trobat errors');
there are 3 '
So the solution is puting in the controller:
@notice="S'han trobat errors".html_safe
and in js.erb:
alert("<%=(@notice)%>");
Of course, I fell in the quotation marks mistake,
but I still have the question: Why in html.erb files are strings auto-escaped, and they aren't in js.erb? so, why is needed to put .html_safe
in the string if I want to show it in js.erb
Upvotes: 0
Reputation: 689
just remove raw or try add .html_safe in js file not in the controller.
Other solution is to use a \' to escape single quote like
@notice="S\'han trovat errors"
Upvotes: 0