Michael Lombardo Michael Lombardo - 1 month ago 4x
Ajax Question

Ajax Delete wont refresh page

Im trying to figure out ajax better! I want to delete a row with an ajax request without the whole page being loaded. The row gets delete but in order to check i have to refresh the page manually. The problem Im having is that after the delete button is clicked the item doesnt get removed without refreshing the page still.

Heres my delete button:

<% current_user.agreements.each do |agreement| %>
<div class="remove-dis">
<div class="requestone" style="border-bottom:solid grey 1px;height:100px;">

<div style="float:left;">

<%= link_to view_scribe_request_path(agreement) do %>
<div class="text-center">
<h><%= agreement.title%></h>

<% end %>

<div style="float:left;">

<div class="text-center">
<h><%= agreement.description%></h>

<%= link_to 'delete', agreement_path(agreement), method: :delete, data: { confirm: 'Are you sure?' }, remote: true, :class => 'delete_request' %>



<% end %>

route is:

resources :agreements

Agreement controller: "holds ajax delete method"

def destroy
@agreement = Agreement.find(params[:id])

respond_to do |format|
format.html { redirect_to my_requests_path }
format.json { head :no_content }
format.js { render :layout => false }

my destroy.js.erb:

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

I have made some changes to the js and html to see what happens when i remove within a list. all listed items will be js removed from the page until refresh. How can I capture only the one listed row?.


The reason this is happening is because your page is rendered by default using the data that exists at the time of the request. It doesn't know when any records are updated, modified, deleted etc. without you telling it that information has been updated.

When you reload the page, you're manually telling your server to fetch the latest data available in the database, hence why you're seeing the correct results after reloading.

You'll either want to remove the item from the DOM using javascript once your server confirms via its AJAX response that the item has been deleted, or, with a little more work, you can open up a real time connection using WebSockets which would notify your front-end immediately when the change occurs.

Most likely, your destroy.js.erb isn't finding the element defined in the following line:

var element = document.getElementById("<%=j @agreement.id %>");

Try keeping track of the ID of the item that you've requested to DELETE on the server before the request was made, and when you're sure it has been removed from the database, you can remove it at that time from the DOM using your javascript.