Use Ruby on Rails in Javascript script - javascript

I try to create my own SonarQube Widget and I have the following question ?
I want to save in a javascript variable the result of my Metrics. The problem is that I don't succeed to use Ruby on Rails with Javascript.
<script type="text/javascript">
var text = "<%= format_measure('sonar.metric.arcadsoftware.rpg.ruleset1') %>";
alert(text);
</script>
If I use just <p><%= format_measure('sonar.metric.arcadsoftware.rpg.ruleset1') -%> </p> the result is "True" on my widget.
So I want to store the String 'True' in my javascript variable text.
Thank you

Related

How to run a javascript string from database in html with rails

i have a this string:
#html = "HELLO <script> alert("this code is from database")</script>"
in my file view .erb:
but dont work
is possible run this code with rails from string?
Bad practice, but it is possible
1 with html_safe
<%- #html.html_safe %>
2 with raw if your variable could be nil
raw(#html)

Assign Javascript value to a java String in a jsp [duplicate]

Can anyone tell me how to pass JavaScript values to Scriptlet in JSP?
I can provide two ways,
a.jsp,
<html>
<script language="javascript" type="text/javascript">
function call(){
var name = "xyz";
window.location.replace("a.jsp?name="+name);
}
</script>
<input type="button" value="Get" onclick='call()'>
<%
String name=request.getParameter("name");
if(name!=null){
out.println(name);
}
%>
</html>
b.jsp,
<script>
var v="xyz";
</script>
<%
String st="<script>document.writeln(v)</script>";
out.println("value="+st);
%>
Your javascript values are client-side, your scriptlet is running server-side. So if you want to use your javascript variables in a scriptlet, you will need to submit them.
To achieve this, either store them in input fields and submit a form, or perform an ajax request. I suggest you look into JQuery for this.
simple, you can't!
JSP is server side, javascript is client side meaning at the time the javascript is evaluated there is no more 'jsp code'.
I've interpreted this question as:
"Can anyone tell me how to pass values for JavaScript for use in a JSP?"
If that's the case, this HTML file would pass a server-calculated variable to a JavaScript in a JSP.
<html>
<body>
<script type="text/javascript">
var serverInfo = "<%=getServletContext().getServerInfo()%>";
alert("Server information " + serverInfo);
</script>
</body>
</html>
You cannot do that but you can do the opposite:
In your jsp you can:
String name = "John Allepe";
request.setAttribute("CustomerName", name);
Access the variable in the js:
var name = "<%= request.getAttribute("CustomerName") %>";
alert(name);
If you are saying you wanna pass javascript value from one jsp to another in javascript then use URLRewriting technique to pass javascript variable to next jsp file and access that in next jsp in request object.
Other wise you can't do it.
Its not possible as you are expecting. But you can do something like this. Pass the your java script value to the servlet/controller, do your processing and then pass this value to the jsp page by putting it into some object's as your requirement. Then you can use this value as you want.
This is for other people landing here.
First of all you need a servlet. I used a #POST request.
Now in your jsp file you have two ways to do this:
The complicated way with AJAX, in case you are new to jsp:
You need to do a post with the javascript var that you want to use in you java class and use JSP to call your java function from inside your request:
$(document).ready(function() {
var sendVar = "hello";
$('#domId').click(function (e)
{
$.ajax({
type: "post",
url: "/", //or whatever your url is
data: "var=" + sendVar ,
success: function(){
console.log("success: " + sendVar );
<%
String received= request.getParameter("var");
if(received == null || received.isEmpty()){
received = "some default value";
}
MyJavaClass.processJSvar(received);
%>;
}
});
});
});
The easy way just with JSP:
<form id="myform" method="post" action="http://localhost:port/index.jsp">
<input type="hidden" name="inputName" value=""/>
<%
String pg = request.getParameter("inputName");
if(pg == null || pg.isEmpty()){
pg = "some default value";
}
DatasyncMain.changeToPage(pg);
%>;
</form>
Of course in this case you still have to load the input value from JS (so far I haven't figured out another way to load it).
I Used a combination of the scriptlet, declaration, and expression tags...
<%!
public String st;
%>
<%
st= "<html> <script> document.writeln('abc') </script> </html>";
%>
<%=
" a " + st + " <br> "
%>
The above code is working completely fine in my case.

Can a js script get a variable written in a EJS context/page within the same file

As I wrote in the title, I'd like to get a value from a variable written into a ejs page/file, from a javascript file within the same page
EJS:
<% var test = 101; %>
JS:
<script>
var getTest = test;
</script>
Or what if I'd like to use a function (with parameter) written into a EJS file and use this function in a JS context where the parameter is given to the function from JS context
EJS:
<% function fn(par){ ... } %>
JS:
<script>
var test = 101;
<%>fn(test)<%>
</script>
Edit: this Half considers you are using EJS on server side
1) You can pass an ejs variable value to a Javascript variable
<% var test = 101; %> // variable created by ejs
<script>
var getTest = <%= test %>; //var test is now assigned to getTest which will only work on browsers
console.log(getTest); // successfully prints 101 on browser
</script>
simply create an ejs variable and assign the value inside the script tag to the var getTest
Ex: var getTest = <%= test %>;
2) You can't pass an javascript variable value to a ejs variable
Yes, you cant: if it is on server.
Why:
The EJS template will be rendered on the server before the Javscript is started execution(it will start on browser), so there is no way going back to server and ask for some previous changes on the page which is already sent to the browser.
Edit: this Half considers you are using EJS on Client side
3) if EJS is on client side, and pass EJS variable to javascript
The answer above will still work, but you will require to load the script within the EJS template, not the script loaded before the template rendered(in that case it will of-course no be a valid javascript).
4) if EJS is on client side, and pass javascript variable to EJS
I m sorry I have myself not tried this case, but I really look forward if someone answers this case
The above answer didn't work for me. You can use a div this way:
<div id="mydiv" data-test=<%= test %>></div>
And access the data variable 'test' that you gave it in a script tag:
<script>var test = document.getElementById('mydiv').dataset.test</script>
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
Solution with a string
<% var test =myString; %> // variable created by ejs
<script>
var getTest = "<%= test %>"; //var test is now assigned to getTest which will only work on browsers
alert(getTest); // successfully prints the string on browser
</script>
Don't forget the quotes around "<%= test %>"
If test is an object, you can use this:
<script>
let getTest = <%- JSON.stringify(test) %>
</script>
Sadly though, depending on what your code editor is, it may be showing that this syntax is bad and will be underlining it with red to mark it as a syntax error. However, this works perfectly fine when you run it.
Inside your <script>,
you can create a div element:
const div = document.createElement('div');
and give it an innerText value like:
div.innerText = `<%= data_from_your_server_response %>`
If you console.log(div), the data from your server response will be displayed.

How to deal with HTML entities in Rails to_json output?

I'm writing an app that uses Rails on the backend and javascript/backbone on the frontend. I'm trying to bootstrap some rails models into my javascript. Specifically, I'd like to load the contents of #courses into a js variable called window.courses. I've got the following in an html.erb file.
<%= javascript_tag do %>
window.courses = JSON.parse('<%= #courses.to_json %>');
<% end %>
I'm expecting the erb preprocessor to render this into valid javascript, like so
<script type="text/javascript">
//<![CDATA[
window.courses = JSON.parse('[{"code":"myCourseCode", ...
//]]>
</script>
... but, instead, I'm getting code that includes HTML entities.
<script type="text/javascript">
//<![CDATA[
window.courses = JSON.parse('[{"code":"myCourseCode", ...
//]]>
</script>
Obviously, I get javascript errors when I try to parse this.
Does anyone know how I can deal with these HTML entities in order to produce valid javascript? I realize that one option would be to unescape the entities on the client side, but this seems like a roundabout solution. Is there a way that I can get Rails to produce JSON that doesn't need unescaping?
If you intend to use raw(obj.to_json) you MUST ensure the following is set.
ActiveSupport.escape_html_entities_in_json = true
The question is solved by my comment, just for the record:
Rails escapes strings that are printed using <%= 'string' %>. By this, it is save to ouput user data.
So, if you don't want Rails to escape the output, you have to tell Rails explicitly by using raw('string').
In your code, that would be:
<%= raw(#courses.to_json) %>

Access Rails global constant in Javascript / jQuery

My setup: Rails 3.0.9, Ruby 1.9.2, jQuery 1.6.2
Rails
constants.rb (initializer file)
DEFAULT_REPLY = "Add a reply..."
Rails
index.html.erb
<%= javascript_include_tag 'reply' %>
...(rest of view code)...
reply.js
$(function() {
var default_reply = <%= h DEFAULT_REPLY -%>;
...(rest of jQuery code)...
});
This throws an error Uncaught SyntaxError:Unexpected token %=, I tried to enclose it in quotes like var default_reply = '<%= h DEFAULT_REPLY -%>' and it output the value as is, meaning default_value has the value of <%= h DEFAULT_REPLY -%>' which is clearly not what I intended. What am I doing wrong?
EDIT
Given the feedback, I have reconsidered and is now using a local variable and jQuery to pull the value from the textarea upon page load.
You need to add .erb to the end of your .js file, along with add the quotes around the string.
The name of your javascript file should be reply.js.erb.
Currently, your .js file is not being run through rails, and is being served statically. That is why when you put the quotes around the string, it output the string '<%= h DEFAULT_REPLY %>' instead of the correct text.
I'd strongly recommend against this approach but I think you're confusing two things here.
Assuming reply.js is in public/javascripts/reply.js, this is a static JS file that is served up by your server. You cannot put any dynamic ("server side") code in here as the file is not evaluated in any manner, just passed back statically.
If you want a global JS variable to use in your files, you'd need to do assign it in your layout file app/views/layouts/application.html.erb or in your action files (index.html.erb, show.html.erb, etc).
Any ERB file is evaluated before returning it, so you could put
<script type='text/javascript'>
$(function() {
var default_reply = "<%= escape_javascript DEFAULT_REPLY %>";
});
</script>
above the <%= yield %> statement of your layout file.
Again, I'd STRONGLY recommend against this approach but if that's why you need, I think this will solve it.
It sounds like you named your view template incorrectly, does it end in .html.erb? If not, it won't evaluate the ERB fragment you pasted.
Once you fix that, you can embed what you want with the following ERB code:
$(function() {
var default_reply = "<%= h DEFAULT_REPLY -%>";
...
});
If it is a rails 3 App why are you using that syntax? try:
var default_reply = <%= DEFAULT_REPLY %>;

Categories