ruby on rails - Rerun JavaScript on successful ajax call -
i have delete button remote: true option set:
# _categories.html.erb <%= link_to 'destroy', category, method: :delete, data: { confirm: 'are sure?' }, remote: true %>
my destroy method uses json:
# categories_controller.rb def destroy @category = admin::category.find(params[:id]) @category.destroy save_to_history("the category \"#{@category.name}\" has been destroyed", current_user.id) respond_to |format| # can't retrieve @categories before attempting delete one. @categories = admin::category.all format.json end end
and destroy.json.erb file looks like:
#destroy.json.erb <% self.formats = ["html"] %> { "html":"<%= raw escape_javascript( render :partial => 'categories', :content_type => 'text/html') %>" }
now problem have javascript run on page load, , deleting initial category works intended... until data changes. need bellow javascript run again every time user changes data either adding new category or deleting category. how? please kind help, not know javascript @ all! haha
<script type='text/javascript'> $(function(){ /* delete category */ $('a[data-remote]').on('ajax:success', function(event, data, status, xhr){ $("#dashboard_categories").html(data.html); }); }); </script>
full index.html.erb:
# index.html.erb <% title "categories" %> <%= form_for @category, remote: true |f| %> <% if @category.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@category.errors.count, "error") %> prohibited category being saved:</h2> <ul> <% @category.errors.full_messages.each |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> <table> <tr> <td><%= f.text_field :name, placeholder: 'category name' %></td> <td><%= f.text_field :color, placeholder: 'colour' %></td> <td><%= f.submit %></td> </tr> </table> <br /> <% end %> <div id="dashboard_categories"> <%= render partial: 'categories' %> </div> <% content_for :javascript %> <script type='text/javascript'> $(function(){ /* new category */ $('#new_admin_category').on('ajax:success', function(event, data, status, xhr){ $("#dashboard_categories").html(data.html); }); /* delete category */ $('a[data-remote]').on('ajax:success', function(event, data, status, xhr){ $("#dashboard_categories").html(data.html); }); }); </script> <% end %>
i don't know if have understand 100% looks want add events after ajax success?
$(function () { function initializeevents() { /* new category */ $('#new_admin_category').on('ajax:success', function (event, data, status, xhr) { $("#dashboard_categories").html(data.html); initializeevents(); }); /* delete category */ $('a[data-remote]').on('ajax:success', function (event, data, status, xhr) { $("#dashboard_categories").html(data.html); initializeevents(); }); } initializeevents(); });
hope helps :)
Comments
Post a Comment