I found two other posts was the same subject in stackoverflow: How to use variable in javascript escape_javascript rails? and How to use variable in javascript escape_javascript rails?
I applied the solutions exposed, and not only did not work, but something weird happened. Well, at least I think it is weird that's a Ruby variable outputs one result when inspected and a totally different result when printed.
I am developing a rails 6 application where The contents of the Files are as follows:
something.html.erb
<%= form_with(url: "/graficos/partido", method: "get") do |f| %>
<%= f.button "ClickMe",
:class => "btn btn-secondary text-white mr-1 active",
:value => "Clicked",
:data => {
disable_with: '<i class="fa fa-spinner fa-spin"></i>'.html_safe
}
%>
<% end %>
<article class="col-9">
<div id="resultquery">
</div>
</article>
something.js.erb
var x=[1,2,3]
x=JSON.stringify(x)
var yt = 99
$("#resultquery").html("<%= j (render :partial => ‘something’,
:locals => {:xt => '_xt_',
:yt => " + yt + "
}
).html_safe
%>".replace("_xt_", x ));
_something.html.erb
<p><%= xt.inspect %></p>
<p><%= xt.class %></p>
<p><%= xt %></p>
<p><%= yt %></p>
And now comes the weird part. The output on the screen shows the following
"[1,2,3]"
String
_xt_
+ yt +
==================================================================
In this example, the approach " … :yt => " + yt + ", … “ Generates the result "+ yt +" (the string itself instead of the value of yt) . Jorawar Singh suggested “=+ yt +-”, Even though I don't understand what this means, it didn't worked to.
The placeholder approach (.replace("xt", x )) generates the weird result:
<p><%= xt.inspect %></p> gives "[1,2,3]", the value I expected to get
<p><%= xt %></p> gives _xt_ (xt[0] => “_”, xt[1] => “x”, ...), the string to be replaced in the something.js.erb file.
My questions are (q1) How can I pass a parameter since the other approaches didn't work. I did something wrong? (q2) What happened in the placeholder approach? I tried it without stringify and the first result was "1,2,3", and the weird second output was the same.