Question

Hello I am newbie in ruby on rails.And I try to do some ajax in my demo website.Delete is performed but I have to refresh each time.

view/shared/_feed_item.html.haml

%li{id: feed_item.id}
= image_tag current_user.image_url(:small_thumb).to_s
%span.user
%span.destination
%b Source:
= feed_item.source
%span.destination
%b Destination:
= feed_item.destination
%span.destination
%b Date:
= feed_item.date
%span.timestamp
%b Time:
= feed_item.time
%span.content
%b Comment:
= feed_item.content
%span.timestamp
- if current_user == feed_item.user
= link_to "Delete", feed_item ,method: :delete, data: { confirm: "You sure?" }, title:  "Delete", remote: true, class: "delete_post"

View/requests/delete.js.haml

$(document).ready(function(){
  $(function(){
    $('.delete_post').bind('ajax:success',function() {
      $(this).closest('li').fadeOut();
    });
  });
});

controller/requests_controller.rb

def destroy
 @request.destroy
 respond_to do |format|
   format.html { redirect_to root_url, notice: "Post deleted" }
   format.js { render nothing: true}
 end
end

raw html link

link

Thanks in Advance.

Was it helpful?

Solution

The reason why jquery not working. problem is turbolinks. $(document).ready(function() is not working with turbolinks. for more look this description

OTHER TIPS

ABPrime,

Can you try with direct jquery as following, if closest doesn't work?

:plain
  $(document).ready(function(){
    $('.delete_post').parent().parent().fadeOut();
  });

I think this is happening because this selector is not finding any elements:

$(this).closest('li')

The jquery closest function traverses up through the DOM, meaning it will look at parents instead of siblings. Instead try to use this:

$(this).prev('li')

You could always put a debugger statements before that line so you can play with a couple of different jquery function for $(this) and see what works best.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top