Im trying to toggle a button without refreshing using ajax
In my micropost_helper.rb
def toggle_like_button(micropost, user)
if user.voted_for?(micropost)
link_to "undo", like_micropost_path(micropost), :class => "btn btn-mini btn-primary", :id =>"unvote_form_#{micropost.id}", :remote => true
else
link_to "Into it!", like_micropost_path(micropost), :class => "btn btn-mini btn-primary", :id =>"vote_form_#{micropost.id}", :remote => true
end
end
In microposts/like.js.erb
$("#vote_form_#{#micropost.id}").html("undo")
$("#unvote_form_#{#micropost.id}").html("Into it!")
I think the syntax is messed up. the #{#micropost.id} part is not working.
replace
$("#vote_form_#{#micropost.id}").html("undo")
$("#unvote_form_#{#micropost.id}").html("Into it!")
with
$("#vote_form_<%=#micropost.id}%>").html("undo");
$("#unvote_form_<%=#micropost.id}%>").html("Into it!");
Related
Sorry for the long title. I don't know how I got stuck this much.
I wanted to have a button (actually a link_to styled as a button) for FOLLOW / UNFOLLOW on remote. That's a Follow model where records are stored for Corporation and User (a User can follow a Corporation). The follow/unfollow links are on the Corporation show page.
<% if user_signed_in? %>
<% if Follow.where(corporation_id: #corporation.id, user_id: current_user.id).first.nil? %>
<%= link_to 'FOLLOW', {:controller => "follows", :action => "create", :user_id => current_user.id, :corporation_id => #corporation.id}, remote: true, :method => "post", class: "btns follow", id: "follow1" %>
<% elsif %>
<%= link_to 'UNFOLLOW', {:controller => "follows", :action => "destroy", :corporation_id => #corporation.id, :user_id => current_user.id }, remote: true, :method => "delete", class: "btns unfollow", id: "unfollow" %>
<% end %>
<% end %>
These are the controller actions:
def create
#corporation_id = params[:corporation_id]
#follow = Follow.new(follow_params)
#follow.save
respond_to do |format|
format.js {render :file => "/corporations/create.js.erb" }
end
end
def destroy
#corporation_id = params[:corporation_id]
attending.destroy
#attending is a method where the follow is defined. This is ok.
respond_to do |format|
format.js {render :file => "/corporations/destroy.js.erb" }
end
end
I'm rendering create.js.erb in corporations, since the change has to happen there. If I leave it as format.js, it'll search in the follows folder which is empty.
The create.js.erb look like this:
$("#unfollow").click(function(){
$("unfollow").replaceWith("<%= escape_javascript(render :partial => "corporations/profile/follow", :locals => {corporation_id: #corporation_id}) %>");
});
Btw, I tried .html instead of replaceWith, but it's not that.
The destroy.js.erb is similar. And the _unfollow.html.erb partial is like this:
<% if !#corporation.nil? %>
<%= link_to 'UNFOLLOW', {:controller => "follows", :action => "destroy", :corporation_id => #corporation.id, :user_id => current_user.id }, :method => "delete", class: "btns unfollow", remote: true, id: "unfollow" %>
<% else %>
<%= Rails.logger.info("First here") %>
<%= Rails.logger.info(corporation_id) %>
<%= link_to 'UNFOLLOW', {:controller => "follows", :action => "destroy", :corporation_id => corporation_id.to_i, :user_id => current_user.id }, :method => "delete", class: "btns unfollow", remote: true, id: "unfollow" %>
<%= Rails.logger.info("Now here...") %>
<% end %>
Without the first condition it just fires up an error the corporation_id (it's same with locales[:corporation_id]) is not defined and similar.
I have no idea what to try now... All the tutorials on the net are quite simple but the remote action is just one action in the controller where it needs to change, this has to go to another controller then back, then again to Follow... I'd really appreciate the help.
I'm generating a link with a confirmation message and am having trouble with how the confirmation message is getting included.
I have tried this with both rails 4.0.10 and rails 4.2.2 and it produces the same output.
Here is my link_to code:
<%= link_to 'Destroy Comment', :url => [comment.article, comment], :method => :delete, :remote => true, :confirm => "are you sure?" -%>
And it generates the following link:
<a data-remote="true" href="/articles/4?confirm=are+you+sure%3F&method=delete&url%5B%5D=4&url%5B%5D=5">Destroy Comment</a>
This is obviously doesn't work because it's putting the javascript confirm message right into the url of the link.
I've found that if I remove the :url => from the link_to it seems to work fine.
<%= link_to 'Destroy Comment', [comment.article, comment], :method => :delete, :remote => true, :confirm => "are you sure?" -%>
<a confirm="are you sure?" data-remote="true" rel="nofollow" data-method="delete" href="/articles/4/comments/5">Destroy Comment</a>
Is there a way to fix this and keep the :url => in the link_to? I really like having the :url => in there for specificity purposes. I looked through the api docs but couldn't find a specific answer. There was one comment made that claims something like this should work. http://apidock.com/rails/ActionView/Helpers/UrlHelper/link_to#1227-link-to-with-as-routing
In your first example, you are passing a hash as second parameter, which matches this method signature:
link_to(body, url_options = {}, html_options = {})
causing Rails to interpret it as url_options, which is why you get that link you get.
If you really want to user the :url=>, then you can create your own helper method, say link_to_with_url that that expects hash containing :url key as the second parameter:
def link_to_with_url(body, options={})
url = options.delete(:url);
if url.nil?
raise "Can't link to something that doesn't have a URL"
else
link_to body, url, options
end
end
You can also overload Rails' link_to method, but I would advise against that.
Try this:
<%= link_to 'Destroy Comment', :url => [comment.article, comment], :method => :delete, :remote => true, :data => {:confirm => "are you sure?"} %>
I have a form_for with remote: :true, but the problem is that it seems to only be submitted remotely about half of the time. Sometimes I will get a ActionController::UnknownFormat (ActionController::UnknownFormat) error from the server, which is configured to only respond to format.js, and most of the time the form will work perfectly.
Is there some way I can call $.rails to make sure that the data-remote binding is taking effect? I have turbolinks turned off. Here is the code for the form:
= form_for [:admin, #seating_chart], remote: 'true', authenticity_token: true, multipart: true do |f|
%br
.form-group.text-center
= f.label :name
= f.text_field :name, class: 'form-control'
.form-group.text-center
= f.label :venue_id
= f.collection_select :venue_id, Venue.all, :id, :name
.form-group.text-center
= f.label :chart_image
= f.file_field :chart_image, id: :seating_chart_file
.actions.text-center
= f.submit 'Save', class: 'btn btn-primary'
\|
= link_to 'Back', :back, class: 'btn btn-primary'
EDIT: upon further investigation it seems to only happen when I upload an image - if I don't upload the image then the error doesn't occur.
Since you are trying to upload file with ajax request it can't be achieved directly.
The solution for this case is remotipart
Remotipart
And this is a demo of it
Demo
I'm trying to allow users to favorite posts and then it show them sort of of interaction through AJAX, but it's not working.
The error I'm getting in the console is:
ActionView::Template::Error (undefined local variable or method `post_item' for #<#<Class:0x007fecb2a3d5f8>:0x007fecb2a357e0>):
The button is being rendered through a partial:
<%= render "shared/fave_form", post_item: post_item %>
Here's the code for the button (shared/_fave_form.html.erb):
<% if current_user.voted_on?(Post.find(post_item)) %>
<%= link_to "unlike", vote_against_post_path(post_item.id), :remote => true, :method => :post, :class => "btn") %>
<% else %>
<%= link_to "like", vote_up_post_path(post_item.id), :remote => true, :method => :post, :class => "btn") %>
<% end %>
Here's the toggle.js.erb file:
$("#fave").html("<%= escape_javascript render('fave_form') %>");
When you render the partial using toggle.js.erb it is not getting locals value post_item, you have to provide it in also.So, your js code should be something like following
$("#fave").html("<%= escape_javascript(render :partial=>"fave_form", locals: {post_item: post_item}).html_safe %>);
I guess you are using some ajax call and then your toggle.js.erb so in your toggle action you must specify value to post_item, lets make it instance variable #post_item so that we can use it in toggle.js.erb.
$("#fave").html("<%= escape_javascript(render :partial=>"fave_form", locals: {post_item: #post_item}).html_safe %>);
The partial is using a local variable, so pass post_item as a local:
<%= render :partial => "shared/fave_form", :locals => {post_item: post_item} %>
I have form to showing all list from some filter form with js and also another button that direct to another action on the same controller BUT still carry the value of the form filter.
For the js things had done properly, but for the the other button, I still confuse.
My BalanceTransactions controller:
def end_period
#some coding
respond_to do |format|
format.html
format.js
end
end
def end_period_close
year=params[:year]
respond_to do |format|
format.html { redirect to goal_path }
end
end
My end_period.html.erb:
<%= form_tag end_period_balance_transactions_path, :method => "get", :id => "headers_search" do %>
<td><%= select_year(Date.today, :prompt => 'Choose year') %></td>
<td><%= submit_tag "Check", :name => nil, :class => "btn btn-info", :remote => true %></td>
<td><%= link_to "Close", nil, :id => "close_button", :class => "btn btn-danger" %></td>
<% end %>
<%= render :partial => 'end_period_table' %>
When I click on [Check] button rails re-render the partial, and it done nicely work with the filter. And I still confuse on how I can deliver the [year] dynamicaly for the [Close] button.
I also done trying with the balance_transactions.js.coffe, which:
$ ->
$("#close_button").click ->
year = $("#date_year").val()
$.get("end_period_close", { year: year })
Sorry for the bad question and grammar, first post.
Thanks and regard,
Kristono Sugiarto
try this one
$ ->
$('#close_button').click ->
$.ajax
url: 'your url here' # appending .erb to the filename gives you access to named routes
data:
year: $('#date_year').val()