Rails 3.2 js.erb file escaping JS - javascript

I am new to rails and I am confused by something.
I am using a js.erb file to show me a list of products fetched from the server. What I am confused at is how I can do this in js.erb file and it works:
<ul class="list-bordered" id="products">
<%= render_cell :businesses, :index, {:businesses => #businesses} %>
</ul>
<%= render :partial => 'partials/infinite', :locals => {:segment => businesses_path, :container => '#businesses'} %>
and every other JS code is escaped, thus
var t = 0;
is output in the page as "var t=0;"
I checked the server logs and the response is indeed JS. I am using respond_with, and checked that I am indeed responding to JS requests.
SIDE QUESTION: Speaking in a "best practice way", is it alright to have html code inside a .js.erb file?
Thanks in advance!

Since you are firing an AJAX request, it's data type is script now and in a .js.erb file you can write Javascript code easily .
$("#products").html("<%=escape_javascript(render_cell :businesses, :index, {:businesses => #businesses}%>")
Now you can manipulate your .js.erb or HTML as per your wish; it's just an example how can you render a partial in a .js.erb.
Now suppose you are rendering HTML on the client side (considering data type is text/html). On an AJAX success, you have to replace that HTML.

Related

Rails and AJAX remote: true what else is required?

I'm confused about remote:true in Rails forms, I thought some Javascript was required to make it asynchronous but this just seems to break my page.
Here is a really simple index.html.haml that includes a partial to show all appointments:
%h1 Calander
%h2 AppointmentsController
%h3 Make a new appointment
= form_for #appointment, remote: true do |f|
= f.text_field :title
= f.text_field :appt_time
= f.submit 'Make appointment'
#appointments
=render 'appointments'
Here is the previously mentioned partial:
-#appointments.each do |a|
%h3= a.title
%p= a.appt_time
Controller methods for index and create:
def index
#appointments = Appointment.order('appt_time ASC')
#appointment = Appointment.new
end
def create
#appointmet = Appointment.create(appointment_params)
redirect_to :root
end
Now this works fine. I can add a new appointment, hit submit and the new appointment shows up without the page refreshing, I think because I have included remote: true. So do I need to add anything else to handle the request? Am I violating best practices by not including something to handle this request and relying entirely on remote: true?
Nothing more required unless you want some callback after ajax call. You did not break any conventions. You can read this document to get ride of confusion.
Let's take a step back.
Web applications can respond to different request formats. Rails has built-in format handling.
So a request might ask for index via HTML, which response with an HTML file. It might also request index via JSON, XML, PDF or even JavaScript.
Whenever you add remote: true you are telling your form make a POST request via JS instead of HTML.
In your views you will have a bunch of HTML.ERB files. These views are request responses.
So to handle a JS request to index, you will need a app/views/appointements/index.js file.
This will be sent as the response to the request and the browser will know what to do with a JS response.
In index.js you can write JS that will be executed once the response is received.
You can also load partials into the page.
For example:
# app/views/appointements/index.js
$('#appointements').html('<%= j render "appointements" %>')
Which will render the partial content as a JavaScript string for the response.
http://guides.rubyonrails.org/working_with_javascript_in_rails.html

How can I render via CoffeeScript in Ruby on Rails 4

I was trying to solve this problem for a while with no result.
I've wanted to pass variables and load a render into a div using CoffeeScript in rails 4.
(I'm using SpreeCommerce platform).
view:
<%= link_to taxonomy.name,root_path+'t/'+tid, {class: "uno", remote: true} %>
controller:
respond_to do |format|
format.html
format.js # menu.js.coffee.erb
end
menu.js.erb.coffee:
$('div#productos').html("<%= escape_javascript(render :partial => /shared/products) %>")
I'd like to load the page '_products.erb.html' and the partial processes the variables that I give it. As soon as I know, view and controller are ok, the problem is in menu.js.erb.coffee
Any help will be apreciated!
ADDITIONAL:
I've modified the extension to .js.coffee.erb. When I try to run the app, it shows me:
"undefined method `render' for #<#:0xa70317c>"
I tryied using <%= raw escape_javascript( render :partial =>... almost always "render" method give me problems.
NEW INFO:
I added gem 'coffee-script' to the Gemfile (then 'bundle install').
Now, when I click the link_to, it shows me into the HTML <%= escape_javascript(render :partial => /shared/products) %> as a text instead of loading the "partial"... any suggestion please?
I wrote a post about this after struggling through the same problem.
You need to:
Name it menu.js.coffee. Suffixing .erb causes it not to be evaluated as CoffeeScript.
Use raw to escape it.
I used these two on my website. Here's how it looks:
<%= raw render 'path/to/menu.js.coffee' %>
It still processes ERB within your CoffeeScript.
I would recommend changing it from menu.js.erb.coffee to menu.js.coffee.erb.
Rails will process the file extensions from right to left. Meaning right now, your file is treated first as coffeescript, then as ruby, and finally as javascript. It looks like you want to make the ruby substitutions first, then parse the coffeescript into javascript, so that would be menu.js.coffee.erb
First of all, you should change file name from menu.js.erb.coffee to menu.js.coffee.erb and you need configuration file as follow, which is a contribution by cervinka on coffee-rails issue #36
config/initializers/coffee_erb_handler.rb
ActionView::Template.register_template_handler 'coffee.erb', Coffee::Rails::TemplateHandler # without this there will be template not found error
class ActionView::PathResolver < ActionView::Resolver
EXTRACT_METHODS = %w{extract_handler_and_format_and_variant extract_handler_and_format} # name for rails 4.1 resp. 4.0
method_name = EXTRACT_METHODS.detect{|m| method_defined?(m) || private_method_defined?(m)}
raise 'unknown extract method name' if method_name.nil?
old_method_name = "old_#{method_name}"
alias_method old_method_name, method_name
define_method(method_name) do |path, default_formats|
self.send(old_method_name, path.gsub(/\.js\.coffee\.erb$/, '.js.coffee'), default_formats)
end
end

Include a Coffeescript file with ERB in a view

This is giving me a major headache...
So I have an app which requires a sidebar that lists various information to do with a user's player. One section of this sidebar is a friends list. Now, when Player A sends a friend request to Player B, the request should be automatically logged in B's sidebar, and I intend to use WebSockets to do this.
Here is my cp.js.coffe.erb file (there's only a few snippets of ERB at the moment; there will be loads more and I rather get this working first):
$ ->
$("#cp").accordion()
if `"WebSocket" in window`
socket = new WebSocket("ws://localhost:8080")
socket.onopen = =>
console.log("Connection Open")
init = {
sender: "cp"
action: "init"
user: <%= #user.id %>
token: <%= cookies["remember_token"] %>
}
socket.send(init.to_json)
socket.onerror = (e)=>
console.log(e)
socket.onclose = =>
console.log("Closed")
socket.onmessage = (m)=>
console.log("Recieved: #{m.data}")
msg = m.data.JSON.parse
switch msg.action
when "ret_init"
when "friend_udt"
refreshFriend()
refreshFriend() ->
html = "<%= j render 'layouts/friends' %>"
$('#friends').empty()
$('#friends').add(html)
Theoretically, the code itself works fine, the problem being that Rails doesn't let you use ERB in the assets pipeline, and so this file has to sit in app/views/layouts.the file cannot access the variables declared within a controller or use the render method (or most other ERB methods).
Here's the thing: I can't include said file in my application.html.erb file, and I looked into requesting the file with AJAX, but from my understanding that will immediately execute the Javascript once and once only, and I need the methods in this to be constantly available to update the sidebar.
Is there any way of including this file so that it works with the ERB and the CoffeScript so that it would be continuously avaliable to the page? Am I misunderstanding the whole AJAX requesting method?
Thanks #nzifnab for your help with the JS. Now my friends partial looks like this:
<ul id="friendlist">
<% if Relation.find_by(owner: #user.id, type: "freq") != nil %>
<% Relation.find_by(owner: #user.id, type: "freq").each do |r| %>
<li class="friend-request-cp"><%= link_to "/#{User.find(r.character).name}" %></li>
<% end %>
<% end %>
<% if Relation.find_by(owner: #user.id, type: "friend") != nil %>
<% Relation.find_by(owner: #user.id, type: "friend").each do |r| %>
<li class="friend-cp"><%= link_to "/#{User.find(r.character).name}" %></li>
<% end %>
<% end %>
</ul>
I need to apply two different styles to each item, hence why I'm using the ERB here. This works fine, as it's loaded when the page is first navigated to, but my code was supposed to re-render that partial every time a notification comes through of any new interactions. It would then repopulate the list using the data from the database again. Is there a more efficient way of doing this? Can I still do this with the hamlcoffeeassets gem you showed me?
Slight tangent ensues:
By the way, I'm using Ruby 2.0.0-p247 and Rails 4 on Windows 7. I felt the need to include that because of some major compatibility issues with gems that are much different from Ubuntu. I had to move from Ubuntu to Windows because updating from 13.04 to 13.10 broke everything Ruby Gem on that OS. I don't have tome to find a fix: I literally have only four days to get this app built.
You can kinda use erb in the asset pipeline, but you have to remember that it only gets rendered ONCE, EVER, and not once for every user and so even if there was an #user variable (which there won't be), it would never change. You can use erb in your coffee file for things like route paths and environment variables, but not for things like user-specific config and dynamic changes to the JS. It's bad practice anyway.
What you should really do is use a javascript library to read cookies instead of trying to do it with rails (This will give you access to some of the things you appear to be trying to do). And when you need more dynamic behavior you should render data-attributes or other values into the html DOM itself and use the javascript to read that.
Take a look at this cookie library: https://github.com/carhartl/jquery-cookie
There's many others to look at via a quick google search.
socket.onopen = =>
console.log("Connection Open")
init = {
sender: "cp"
action: "init"
user: $.cookie('user_id')
token: $.cookie('remember_token')
}
There are a couple of ways to render new markup for your view using JS. One way is to use js templates. I'm a big fan of the hamlcoffeeassets library here: https://github.com/netzpirat/haml_coffee_assets Although it uses haml for the view, and not ERB. There are ERB variants as well.
You would add some markup to app/assets/templates/friend.jst.hamlc like so:
%p This is my friend markup #{#friend.name}
And then you can render it from your JS like this:
$('#friends').append(JST['templates/friend'](friend: {name: 'Bob'}))
Which will append the markup from your template with the values you've passed interpolated in. In my example you'd end up with this markup inside your #friends container:
<p>This is my friend markup Bob</p>
Alternatively you can render the partial you want via rails into your JSON response as just a string, and then insert that into your document...
So your JS might look something like this:
socket.onmessage = (m)=>
console.log("Recieved: #{m.data}")
msg = m.data.JSON.parse
switch msg.action
when "ret_init"
when "friend_udt"
refreshFriend(msg.friendHTML)
refreshFriend(html) ->
$('#friends').html(html)
UPDATE
In reference to your ERB question... First of all your partial is incredibly inefficient making similar calls to the database four times every time you render it. haml_coffee_assets is for use with the haml markup language (which I prefer over ERB), if you want ERB then use eco instead: https://github.com/sstephenson/eco
If you want to render this in the JS, then you need to send this "friend relation" data as JSON through the notification data response, you do not have access to active record OR any controller methods or instance variables when rendering javascript partials - they don't hit back to the server, they only use what is accessible by your javascript at the time.
This should really go to app/assets/javascripts/cp.js.coffee.erb, you can use erb in the asset pipeline just fine (see here) Make sure you are spelling the coffee extension right, though!
Doing this, you should be able to call this via ajax without problems, the path would be /assets/cp.js.
try this gem: 'coffeebeans'
name your coffee file as "some_file.html.erb"
<%= coffeescript_tag_do %>
# your coffee script here ...
<% end %>
in another erb file:
<%= render file: '.../some_file' %>

Can server side loop be done in javascript/ajax?

How can I loop server side code on the client without javascript? I have this loop in my rails app
//partial = _manufacturers
<div id="all_manufcaturers">
<% for manufacturers in #manufacturerss%>
ID: <%= h manufacturers.id %>
<% end %>
</div>
How can I render this using ajax? I know something like the following works since it is just a static replacement:
$("#manufacturers_count").html('Manufacturer - <%= #car.manufacturers.count %>');
But pseudocode like this does not work since the partial contains a loop:
$("#all_manufacturers").html('...render(manufacturers)...');
Yes, it can be done. You will want to make a server side script (e.g php) that builds a dataset for you and echos it with json_encode. You will then want to parse the response from the request with the appropriate javascript decode function in whatever library you're using (example, jQuery.decodeJSON()). You can then loop through the response set and render.

Rails 3 make ajax using jquery and execute .js.erb

I have the following haml code:
%input{:value => "", :type => "button",:class => "SendBtn", :onclick => "$.get('#{send_path}',{parameter:$('#parameter').val()}); "}
This input executes an event in the controller.
// This is my controller
def send
if request.xhr?
// do stuff
end
end
But my js code in the corresponding .js.erb file is not being executed. It is returned as the response of the get request.
// send.js.erb
alert('hello');
How is the rails way to have this code executed?
Your problem is not Rails related, it's jQuery. With the get method you are just fetching more or less plain text. This will not get executed. You could do an eval on the text but there is a better way. Use the getScript method from jQuery. This will fetch and execute your code.
As a side note, there are two things that are bothering me in your code:
You are using inline JavaScript. try to remove this by using a data- attribute for your send path, like this data: { sendPath: send_path }, and retrieving it with $(yourInput).data('sendPath') in your application.js file.
From my personal view I do not like to put executing JavaScript code in ERB templates. I find that this fragments the front end logic of my app. For me it worked better to put the logic in .js files and communicate with the server over JSON.
As #topek said, you have to use $.getScript. Also in your situation better approach is to use button_to with :remote => true property instead of plain input.
<%= button_to "Do Something",
{ :controller => :somecontroller, :action=> :something },
{ :remote => true }
%>
Also you can pass attributes to button_to (but you have add parameter to your route definition).
<%= button_to "Do Something",
{ :controller => :somecontroller, :action=> :something, :param => #object.id },
{ :remote => true } %>
Here goes documentation for button_to: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-button_to

Categories

Resources