How can I pass to Ruby obj to Javascript? - javascript

I have this to calling the choose_category:
{ :action => :choose_category, :id => category } do %>
And I have this method to calling the choose_category.js.rjs:
def choose_category
begin
category = Category.find(params[:id])
rescue
ActiveRecord::RecordNotFound
logger.error("Attempt to access invalid product #{params[:id]}")
# flash[:notice] = "Invalid product"
redirect_to :action => :index
else
respond_to { |format| format.js }
# redirect_to_index
end
end
I want to call back the category name, how can I do that? I try this, but it return nothing for me.
page.alert(#category.name)

Your problem is that #category isn't defined in your RJS template.
RJS files are essentially views that generate Javascript. Like views, they have access to instance variables set in the controller, but not local variables.
Putting this in the begin section of your action should solve your problem.
#category = Category.find(params[:id])

I'm not sure of this since I'm not very familiar with js and rjs, but I would add to your rjs something like this:
category_name = <%= #category.name %>;
and then
page.alert(category_name)
or just:
page.alert(<%= #category.name %>)

If you can write your own JavaScript why not use the Ruby's to_json() method to output your object in JSON to an embedded constant on your page and then write some JavaScript to access this variable and manipulate as needed?

Related

ruby on rails rendering json in js.erb

In a create method in controller I have the following code:
respond_to do |format|
format.js { render json: { html: render_to_string(partial: '/users/photos/card', object: #photo, as: 'photo') } }
end
which works perfectly. Now I would like to move this in create.js.erb to have the possibility to execute additions js. However I do not figure out how to render the json above in create.js.erb.
Any idea how to accomplish this. Thanks in advance!
If I understood you right, what you are trying to achieve is to be able to access your JSON inside a js.erb view. In order to accomplish that, what I've done in the past is the following:
In your create.js.erb:
var yourJSON = JSON.parse("<%= raw(j render :partial => '/users/photos/card', object: #photo, as: 'photo') %>");
And in your controller:
respond_to do |format|
format.js # This will render the create.js.erb
format.json { render :partial => '/users/photos/card' } # Leave this one in case you also want to be able to respond to this format i.e: "http://localhost:3000/users/photos/card/id.json"
end
Hope this helps!
P.S: Let me know if you were trying to achieve something different.

Ruby on Rails -> Create div dynamically

I work on a task manager app, and I want to create html div 'cards' (with title, duration etc...), with all the datas I got on a database in rails.
I guess that I have to use javascript functions, but I can't get a way to do it.
I saw a lot of things on google, but I can't find exactly javascript calls from a rails controller (because I only catch all datas in the controller).
Here is my controller :
def new
# Retrieve all tasks in the project
#taskModel = Task.new()
#projectTasks = #taskModel.getProjectTasks()
# Add tasks on html
(0..#projectTasks.length).each do |i|
respond_to do |format|
format.js { render :js => "window.createTask();" } # I need to pass parameters in the createTask function
end
end
end
and my js file :
window.createTask = (title, content, duration) ->
card = document.createElement('div');
document.getElementsByClassName('content')[0].appendChild(card);
With my code, I get this error : ActionController::UnknownFormat
ActionController::UnknownFormat indicated that your ajax request is interpreted as a request with the wrong format. To answer this part better you'd have to post the javascript with the ajax call.
Secondly, you have to rethink the render in this block
(0..#projectTasks.length).each do |i|
respond_to do |format|
format.js { render :js => "window.createTask();" } # I need to pass parameters in the createTask function
end
end
You are calling respond_to multiple times which is just wrong. Put this loop into a new.js.erb view.

Rails: pass data to javascript [duplicate]

This question already has answers here:
How to pass Ruby variables to a JavaScript function in a Rails view?
(6 answers)
Ruby on Rails - Send JavaScript variable from controller to external Javascript asset file
(2 answers)
Closed 8 years ago.
i'm new in Rails and in a controller i have:
class PagesController < ApplicationController
def home
#temp = "Hello"
end
end
I have read that i must put the javascript code in application.js (tell me if true) and i have:
window.onload=function(){alert("<%= j #temp %>")}
Obviously that alert print the string "<%= j #temp %>"
How can i pass the variable #temp to the javascript so that the alert can print Hello?
Thanks
I wrote an article on how to pass Ruby objects to the client. Ryan Bates also has an excellent RailsCast on passing data to JS.
Add a div to your view that corresponds to your the PagesControlle#home action that will not be visible when you load the page but will contain the data stored in the Ruby objects:
# views/pages_controllers/home.html.erb
<%= content_tag :div, class: "temp_information", data: {temp: #temp} do %>
<% end %>
Load the page with this div included and view the page source. You can see your Ruby objects stored in the .temp_information div. Open up the JavaScript console to access the Ruby objects as JavaScript objects:
$('.temp_information').data('temp')
You do not need to add your JS to a JS partial, you can also use the asset pipeline.
I do something similar to, but simpler than gon. I have the following in my ApplicationController.
def javascript_variables(variables)
#javascript_variables ||= {}
#javascript_variables.merge!(variables)
end
Within a controller action I can then do something like
def some_action
javascript_variables(user: current_user)
end
In my ApplicationHelper I have something like this
def javascript_variables(variables = nil)
#javascript_variables ||= {}
#javascript_variables.merge!(variables) and return if !variables.nil?
output = ''
padding = #javascript_variables.keys.group_by(&:size).max.first
#javascript_variables.each do |variable, value|
output << "#{variable.to_s.ljust(padding)} = #{value.to_json},\n "
end
raw "var " + output.strip.html_safe.gsub(/\,\Z/m, ';')
end
and finally in my layout's <head> I have
<script>
<%= javascript_variables %>
</script>
This gives me something like this (from a real example in my application)
<script>
var pageModule = "site/index",
isCustomer = false,
utype = "normal",
isAnonymous = true,
keyboardShortcuts = false,
pubnub = null,
requestToken = "3zj974w074ftria3j";
</script>
Take a look at this.
http://tech.thereq.com/post/17243732577/rails-3-using-link-to-remote-true-with-jquery-ujs
One of the easiest ways is to use js.erb file, where you can do ruby tags to access variables that you defined in the controller action.
You need to use a respond_to block in the controller action, specifying the action to be able to respond to javascript.
items_controller.rb
class ItemsController < ApplicationController
def action
respond_to do |format|
format.js
#format.html {} # These are for allowing other types of formats to be responded to.
#format.json {} # But they are not necessary for using this js.erb way of doing things.
end
end
end
/views/items/action.js.erb
$(div).html('The cat has erased your page');

sending variable to a javascript file in RoR

I am using ajax to call a RoR rails function and am new to this.
The function is
def destroy
#fav_company = FavouriteCompany.find(params[:id])
respond_to do |format|
format.js { render :layout=>false }
end
end
In my destroy.js.erb I have
$('#profile_alerts').show();
$('#Fav#{#fav_company.id}').hide();
The first line is working but not the second line. I am suspecting it is unable to access #fav_company.
What should I do? thanks
=====
Some additional information, the call I am making to this function is a link_to with remote => 'true' as such:
<%=link_to "destroy",{:controller=>"favourite_companies",:action=>"destroy", :id=>"#{fav.id}"}, {:remote => true } %>
This:
$('#Fav#{#fav_company.id}').hide();
Should be:
$('#Fav #{#fav_company.id}').hide();
Assuming #fav_company.id presents a variable in the DOM
Since your javascript code is in an ERB file I think you should be using $('#Fav<%=#fav_company.id%>').hide();.
Try to use:
$('#Fav#{escape_javascript({#fav_company.id}).html_safe}').hide();
==================================================================================
Ok, my code, but I does another task:
albums/show.html.haml
= link_to t('write.comment'), new_album_comment_path(#album, :format => :js, :id => #album.id), :remote => true
comments/new.js.haml
$("#comment_form").html("#{escape_javascript(render :partial => "comments/form").html_safe}");
also all code here https://github.com/barthezslavik/mebel - if you found something useful, I'll be happy

jQuery/Rails 3 button does not change state

I have spent a couple of days (like 4) trying to solve this issue. I followed the Hartl Rails 3 tutorial and in chapter 12 tried to convert the site from prototype to jQuery. I am not able to get the "follow"/"unfollow" button to update however.
I am able to issue jQuery commands from within Safari's Inspect Element Console, but if I put even the simplest jQuery command into the destroy.js.erb or create.js.erb files, nothing happens. The log is indicating that the appropriate relationships/destry.js.erb (or create.js.erb) file is rendering.
Here is the code that I have in the controller:
class RelationshipsController < ApplicationController
before_filter :authenticate
def create
#user = User.find(params[:relationship][:followed_id])
current_user.follow!(#user)
respond_to do |format|
format.html { redirect_to #user }
format.js
end
end
def destroy
#user = Relationship.find(params[:id]).followed
current_user.unfollow!(#user)
respond_to do |format|
format.html { redirect_to #user }
format.js
end
end
end
The users/_follow.html.haml is
- relationship = current_user.relationships.build(:followed_id => #user.id)
= form_for(relationship, :remote => true) do |f|
= f.hidden_field :followed_id
.actions= f.submit "Follow"
The users/_unfollow.html.haml is
- relationship = current_user.relationships.find_by_followed_id(#user)
- delete = { :method => :delete }
= form_for(relationship, :html => delete, :remote => true) do |f|
.actions= f.submit "Unfollow"
The users/_follow_form.html.haml is
- unless current_user?(#user)
#follow_form
- if current_user.following?(#user)
= render 'unfollow'
- else
= render 'follow'
The relationships/create.js.erb is
$("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>")
$("#followers").html('<%= "#{#user.followers.count} followers" %>')
The relationships/destroy.js.erb is
$("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>")
$("#followers").html('<%= "#{#user.followers.count} followers" %>')
However, in trying to diagnose this, I tried a very basic
$("#title").html("Followed")
which also does not work.
Looks like an issue with how you're using jQuery.
jQuery uses CSS-style selectors, while Prototype doesn't. So, to make it work, just add a "#" symbol to the selectors.
Instead of
$("follow_form").html("something");
You should use
$("#follow_form").html("something");
// Note the # symbol in the selector.
// Also, remember to end your statements with a semicolon.
You can read about jQuery ID selectors here: http://api.jquery.com/id-selector/
Check your public folder for an Assets folder, with application.js in it. Not sure how I ended up with that, but that was causing ajax queries to be processed twice.
It looks like you might be using Rails 3.1. It's important to use the exact gem versions used in the tutorial (including Rails 3.0 instead of 3.1) if want the same results. See the debugging tips at the Rails Tutorial Help page for more suggestions.

Categories

Resources