outputing ruby strings in js.erb file - javascript

I am making some ajax call and in my js.erb file I put
$("body").append(<%= escape_javascript(render("layouts/some_layout")) %>);
I had no output in my html file, but in my log, render("layouts/some_layout") is correctly called. So for debugging purpose, I put
$("body").append(<%= j "<div>test</div>" %>);
But this also output nothin. Why is it so ?

I guess you should have your erb code enveloped with quotation marks, otherwise you'll probably get JS syntax error:
$("body").append('<%= escape_javascript(render("layouts/some_layout")) %>');

Related

How to render html.erb file to assets/javascript?

Below is the code I have in my assets/javascripts/investment.js file:
investment_updates.forEach(function(investment_update, n){
data.push(new Item((n+1)*space, (n+1)*space, (n)*angle));
add(n+1, "<%= render '/investment_updates/single_investment_update', investment_update: investment_update %>")
});
I want to render views/investment_updates/_single_investment_update.html.erb file in my javascript file and I tried below code but didn't work.
<%= render '/investment_updates/single_investment_update', investment_update: investment_update %>
Help me to render partial in my js file as a parameter.
Your js file should end in .js.erb instead, so it will be picked up by the Rails Asset Pipeline.
Note though that the way you are inserting data in a string is quite brittle. One misplaced ' or " can break your Javascript

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)

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 %>;

How to pass a javascript variable into a erb code in a js view?

I have this Javascript view in my Rails 3 project:
app/views/expenses/new_daily.js.erb
var i = parseInt($('#daily').attr('data-num')) + 1;
//$('#daily').append('agrego fila ' + i + ' <br />');
$('#daily').append('<%= escape_javascript(render(partial: 'new_expense', locals: { i: i })) %>');
$('#daily').attr('data-num', i);
I want to pass my 'i' javascript variable to a ruby partial through locals, How I can accomplish this?
As far as i know there is no way to do it directly and the reason is fairly simple too, html is executed at the server side and javascript is a client side language which means its executed in your local browser, thats why if you even try to pass a variable between the two you'll have to make a request to the server,
However this problem is tackled by calling an AJAX request, this AJAX request does the same thing as sending a new request to the server however it does that without refreshing or reloading the page to it gives the users the illusion that no request was made.
a guy asks a similar question Here
and you can learn more about AJAX Here on MDN:
Yes you can pass the value by using jquery;
<%=f.text_field :email ,:id=>"email_field" %>
<script type="text/javascript">
var my_email= "my#email.com"
$(document).ready(function(){
$("#email_field").val(my_email);
});
</script>
Simple answer is you can't. Partials are expanded at server side, and JavaScript variables are set later at client side. You could make i (as a variable name) a parameter of the partial and use it there.
render :partial => 'xx', :locals => { :variable => 'i' }
And in partial
alert(<%= variable %>);
Check out the gon gem. https://github.com/gazay/gon
It gives you a simple object you can pass variables to that will be available to your scripts via window.gon
Also referenced here
http://railscasts.com/episodes/324-passing-data-to-javascript
1) You may create a js tag with global variable in you erb template, after that you will be able to access that variable from any js file
<%= javascript_tag do %>
window.productsURL = '<%= j products_url %>';
<% end %>
2) You can pass data to data-attribute in erb template and access it by js on client side that way $('#products').data('products')
<%= content_tag "div", id: "products", data: {products: Product.limit(10)} do %>
Loading products...
<% end %>
3) You can use gon, to use your Rails variables in your js
There is a good article, read it and fine solution for your specific case
http://railscasts.com/episodes/324-passing-data-to-javascript,
more comments are here http://railscasts.com/episodes/324-passing-data-to-javascript?view=asciicast
Here's a few different options on how to do it:
http://jing.io/t/pass-javascript-variables-to-rails-controller.html
The best other answers here are right that this can't be done by passing the javascript variable into an erb partial, since it is rendered on the server, not the client.
But since anyone looking for this is probably interested in a work-around solution, which I don't see here, I will post this example that works well with Rails UJS and Turbolinks.
First, you set up your controller to return a partial as HTML:
format.html { render partial: "new_expense" }
Next, write a javascript AJAX function in app/views/expenses/new_daily.js.erb:
var i = parseInt($('#daily').attr('data-num')) + 1;
$.ajax({
url: '/daily',
type: 'GET',
dataType: 'html',
contentType: "application/html",
success: function(response) {
$('#daily').replaceWith(response)
$('#daily').attr('data-num', i);
}
});
This is going to get your Rails partial as an html fragment that you can use to replace that part of your rendered page. You can use jQuery to get your data-num attribute value, do some math on it, replace the partial in your view, and then set the attribute value again.
You may ask why go to all the trouble of getting the Rails partial and replace it on the page, instead of just getting the data attribute, doing math on it, and setting that? The answer is that this is the best, and perhaps the only way of doing something which is really essential when rendering a Rails partial using UJS while handling an asynchronous response to an action.
If you are handling an asynchronous response from your server in a create.js.erb template, then your variables (#daily, for example) are not going to reflect the work done after the request has completed (for example, if there has been processing on a background server like Sidekiq). In that case you don't have up-to-date action response variables to pass into your Rails partial in the js.erb file, but you also can't pass the javascript data response into your partial, as pointed out in this question.
As far as I know, this approach is the only way to get a fully up-to-date partial after receiving a response to an asynchronous response (not shown). This get you the up-to-date partial, allows you to get your javascript into it, and is flexible enough to work in pretty much any use case.
Let's make shure we understand each other. Your erb template (new_daily.js.erb) will be processed on the server side, ruby code will be evaluated (within <% %>), substitution made, and then resulting javascript will be sent to browser. On the client side the browser will then evaluate this javascript code and variable i will be assigned a value.
Now when do you want to pass this variable and to what partial?

Categories