jacques Mesnet jacques Mesnet - 2 months ago 8
Ajax Question

My Ajax is not working

I'm learning Ajax, which is great, but I encounter some difficulties on the implementation of it.
I would like to call a fadeOut the element #group_box when a user click on a button #rem_req_btn.

My code is working only on the first element of my list, but not the others one. I've try to add the group id in the div but is not working.

Anyone can help me to find the better way to achieve this action ?

Index group :

<% @my_groups.each do |group| %>
<div id="group_box">
<%= render 'group', group: group %>
<% end %>

_group :

<div class="col-md-3">
<div class="panel panel-default">
<div class="panel-heading">
<h3 style="margin-top:5px; text-align:center">
<div class="panel-body">

<div class="panel-footer" style="height: 50px; padding:7px;">
<div class="btn btn-default">
<i class="fa fa-tasks" aria-hidden="true"></i>
<%- unless group.main? %>
<%= link_to rem_req_group_path(group), method: :patch, data: {confirm: "Etes vous sur de vouloir sortir de ce groupe ?"}, id: "rem_req_btn", remote: true do %>
<div class="btn btn-danger pull-right">
<i class="fa fa-sign-out" aria-hidden="true"></i>
<% end %>
<% end %>


Ajax file:

$('#rem_req_btn').bind('ajax:success', function() {

Answer Source

Change following

Index Template <div id="group_box"> to <div id="group_box#{group.id}">

Remove JS code from your index page

$('#rem_req_btn').bind('ajax:success', function() { $(this).closest('#group_box').fadeOut(); });

Create a .js.erb template at the level of index.erb with name equal the action name. eg. if rem_req_group_path(group) is mapped to rem_req_group action in your controller where the request is landing when you click the link then the name would be rem_req_group.js.erb

Now in rem_req_group.js.erb write following