Inserting javascript values into erb code - javascript

I have a js.erb template with the following code:
var latlng = new google.maps.LatLng(<%= session[:lat] %>, <%= session[:lng] %>);
I'm now trying to do the opposite (insert javascript into ruby):
<% session[:lat] = javascript_tag("document.write(location.lat());") %>

I think you're missing the point of Javascript.
Ruby code (<% .. %> parts in your examples) is run on the server.
Javascript code (var latlng = new google.maps.LatLng(10, 20); and document.write(location.lat());) is executed in the browser.
It's also executed after ruby code, when server has processed request and generated result page already.
If you want to know value of location.lat() on the server, you'll have to send it from the browser to the server in AJAX request. Any popular Javascript library will help with that.

Maybe you could try <%= raw [ruby/rails code] %>
This link may help: http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/a160d9c2e55cfe36

Related

Rails - HTTParty request through AJAX

I am new to both Rails and AJAX.
I want to consume an API which is hosted on a different website. I ran into problems with cross origin HTTP request. So I tried doing this by using HTTParty.
In the code below, I am setting the text of $(".result") as JSON.parse(HTTParty()) request, so that it can query the website and give me the result.
Rails code:
<%= form_for(#profile) do |f| %>
<%= f.label :content %>
<%= f.text_field :content, class: 'ajax-control' %>
<%= f.submit "Save changes", class: "btn btn-primary" %>
<% end %>
<p class="result"></p>
Javascript code:
<script>
$(document).ready(function(){
$('.ajax-control').on('keyup',function(){
var charCount = $(this).val().length;
if(charCount===3){
var str1='<%=JSON.parse(HTTParty.get("http://example.com/api.php?param='+$(this).val()+'"))%>'
$(".result").text(str1);
}
});
});
</script>
Now comes the weird problem. The code above does send the GET request to example.com (placeholder), but gets a response saying that it is not a valid query.
However, if I pass the str1 as follows -
var str1='<%=JSON.parse(HTTParty.get("http://example.com/api.php?param=xyz"))%>'
$(".result").text(str1);
I get the expected response. If the $(".ajax-control") text field is "xyz", I get a response saying not a valid query.
Does string concatenation in javascript introduces new characters because of which it is throwing an error?
That javascript (which in turn has ruby code via erb) is not going to execute after its been rendered the first time by Rails.
That is, its not going to be invoked each time that keypress callback is called, which means that when Rails is rendering that Javascript it obviously has no knowledge of the client-side DOM so the URL is affectively:
JSON.parse(HTTParty.get("http://example.com/api.php?param="))
And the remote server has an empty param which it doesnt like...
If you really need to invoke that API for every keypress you have two options:
Get it to work via Ajax using CORS
Invoke an endpoint in your Rails app,
which in turn uses Ruby-side HTTParty to invoke the API and relay
the response back to the client.

Javascript variables in ruby code

In my RoR project I got html page, where I changing div's background image with javascript. Javascript function send me index, and I want to use this index for getting element of ruby array.
Look into my code
function drawNewProject (index){
console.log(<%= 'index' %>)
<% index = 'index' %>
<% #existProjects = Admin::Project.order('weight') %>
<% #existProject = #existProjects[index] %>
var image = document.getElementById('block_one')
image.style.backgroundImage="url('<%= #existProject.image(:large) %>')";
}
But this line
<% #existProject = #existProjects[index] %>
Gives me error
no implicit conversion of String into Integer
Do you know how to do it correct? Thnx.
You have to think that the <%= erb %> block is executed in the server before being sent to the browser, and once there, the javascript is run.
Your browser has no idea about ruby or php or whatever... it just receives the html and the js (regardless is a static file, or a dynamically generated bunch of js) and runs it.
That means that all the data must be known at rendering time. If your application depends on dynamic data, or on your user interaction, then you have to do an ajax request and deliver back a call with the right js to be run by the browser.

Converting JS to CoffeScript, missing operand?

I've got a HighCharts javascript that i'm trying to convert to CoffeeScript, using some online converters.
However all of them error out with "missing operand"
Here's the code
$(function() {
$('#container').highcharts({
series: [{
name: "<%= x %>'",
data: [
<% #sprice = #price * #quantity %>
<% 0.upto(#years).each do |stack| %>
<%= number_with_precision(#sprice, precision: 2) %>,
<% #sprice = ((#sprice*percentage)/100)+#sprice %>,
<% end %>]
}]
});
});
Where's the missing operand tho? Does it have something to do with embedded ruby inside my JS script?
Script is working as intended inside HTML view file. But i'm trying to move it into controller's js file to clean it up abit. Controller's js file is in coffescript by default, so that's where im kind of stuck.
Any help appreciated, thanks!
As noted above:
If #years is small
then ERB a couple simple scalars and then build the array in CoffeeScript;
If #years is large
then do the heavy lifting in your controller and stuff the data into your CoffeeScript as a one line JSON blob.
Or AJAX it or split the data out into a separate piece of JavaScript and leave the code as CoffeeScript.
References
CoffeeScript, TypeScript? How about JavaScript

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