Successful AJAX delete functionality without page refresh

After extensive searching, I still can't seem to figure out why The Pit is deleting according to my logs but the changes aren't reflected on the page until I manually refresh. This is my first time working with JS in my app so it's a learning process for me. Any insights would be greatly appreciated.

Here's what my log says:

Started DELETE "/pits/25" for 127.0.0.1 at 2014-09-01 00:20:45 -0500
Processing by PitsController#destroy as JS
  Parameters: {"id"=>"25"}
  User Load (0.4ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 1  ORDER BY "users"."id" ASC LIMIT 1
  Pit Load (0.3ms)  SELECT  "pits".* FROM "pits"  WHERE "pits"."user_id" = ? AND "pits"."id" = 25 LIMIT 1  [["user_id", 1]]
   (0.1ms)  begin transaction
  ActsAsVotable::Vote Load (0.1ms)  SELECT "votes".* FROM "votes"  WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ?  [["votable_id", 25], ["votable_type", "Pit"]]
  SQL (28.1ms)  DELETE FROM "pits" WHERE "pits"."id" = ?  [["id", 25]]
   (1.3ms)  commit transaction
  Rendered pits/destroy.js.erb (0.6ms)
Completed 200 OK in 111ms (Views: 37.7ms | ActiveRecord: 30.2ms)

Index view:

<div class = "container list-pits"> 
  <%= link_to "Add New Pit", new_pit_path, class: "btn btn-default" %>
  <br>
  <br>
  <% @pit.each do |pit| %>

   <div class = "container">
    <div class = "well pit-index"> 
       <h3 id="pit-title"><%= link_to pit.topic, pit_path(pit) %></h3>
       <p>by <%= link_to pit.author, '#' %></p>
          <br>
            <p><%= pit.summary %></p>
            <p>Replies (<%= pit.comments.count %>)</p>
          <br>
            <p>Pit Created by: <%= link_to pit.user.name, pit.user %> on <%= pit.created_at %></p>
            <%= link_to "View Pit", pit_path(pit), class: "btn btn-primary" %>
          <%= link_to pit_path(pit), remote: true, method: :delete, data: { confirm: 'Are you sure?' } do %>
            <button class = "btn btn-primary">Delete!</button>
            <% end %>
      </div>
    </div>
      <% end %>
 </div>

Controller Action:

def destroy
  @pit.destroy
end

destroy.js.erb:

$('.pits').html("<%= j (render @pits);

Answer №1

Let's get started:

#app/views/pits/destroy.js.erb
$('.pits').html("<%= j (render @pits) %>");

Explaining Ajax in RoR

If you're new to RoR / Ajax, here are some tips to help you understand the process:

When you send an ajax request, you'll receive a response from the server. It's important for you as the developer to handle this response effectively in your application.

Always remember that ajax always sends a response - it's up to you how you want to handle it.

--

In Ruby on Rails, there are two types of Ajax responses you can work with:

  1. "Standard" Ajax response handling
  2. Rails-based response using the views system

Both methods achieve the same goal but differ in how they are implemented.

The "standard" ajax response method allows you to capture and manipulate the response within the ajax call itself:

$.ajax({
  ...
  success: function(data) {
     ...
  }

This method enables you to work with the raw data from the server response. However, you can only use the data received through the ajax response unless specified otherwise.

The other approach is the "Rails" way of utilizing Ajax which involves creating functionality that Rails server will render under the views directory, allowing you to utilize Rails-specific methods:

#app/controllers/pits_controller.rb
class PitsController < ApplicationController
  respond_to :js, :html, only: :destroy

  def destroy
     @pit = Pit.find params[:id]
     @pit.destroy

     respond_with @pit
  end
end

#app/views/pits/destroy.js.erb
// you can access @pit here
$('.pits').html("<%= j (render @pits) %>");

Understanding Ajax Concept

Ajax is a method of sending asynchronous requests from your browser to the backend server:

To put it simply, each ajax request you make is a new interaction with the server due to the statelessness of the HTTP protocol. By using Javascript, you can trigger new requests and receive responses from the server without reloading the page.

The nature of the response depends on your backend coding, but essentially, ajax allows you to exchange data beyond traditional HTTP requests. In essence, ajax requests function similarly to standard requests but are facilitated by Javascript.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In Vue, it is not accurate to measure overflow

I am working on creating an overflow effect with tagging that fades out at the beginning to provide a subtle hint to users that there is more content. Here is what it currently looks like: https://i.stack.imgur.com/fXGBR.png To achieve this, I added a fa ...

What are some strategies to optimize image loading speed in an HTML5 mobile application?

I have a HTML5 mobile application where I am loading 10 images at a time from imgur when the user clicks a button. After retrieving the images, I am applying CSS formatting to adjust the height and width for proper display on an iPhone. I suspect that the ...

Creating a dynamic chart on the fly with the power of chart.js

Currently in the process of building a data dashboard and have hit a roadblock that I can't seem to navigate. Utilizing chart.js for rendering charts and jquery/js for dashboard control, I aim to allow users to add new charts with a simple button clic ...

Retrieve documents from mongodb that were created in the past half hour

Currently, I am in Central European Summer Time (CEST) and at 15:08, I added a document to my collection. When passing timestamps: true to a new Schema, the createdAt time is showing two hours too early: createdAt:2019-08-21 13:08:39.219 Why is this happ ...

utilizing d3 version 4 to overlay d3 paths on google maps

I am working with a code snippet that integrates a google map and appends a layer over it. However, I have encountered an issue with the projection causing an error and preventing the layer from displaying on the google map alone. Any assistance in resol ...

What is the best way to send two mongoose find queries to the correct GET route?

I am facing an issue with my app where I have two separate routes using app.get to render "/" and fetch data from two different MongoDB collections using mongoose find{} methods. I also have corresponding post routes that redirect the data entered in forms ...

Retrieve several documents from an FTP directory via an AJAX request using a servlet or Java

I need to download multiple files from an FTP location directly through a web application using an AJAX call. I have tried one method of copying the files to the server from FTP, converting them to a ZIP file, and then downloading. However, I don't w ...

How to Transfer Data from a Dynamic Drop-down Menu to PHP for Processing and Presentation in a Div Element on the Same Web Page

I've scoured various online resources, including StackOverflow, but haven't been able to find a solution for this issue described in the title. On my base page, I have a dynamically generated dropdown list as shown below: <div class="tipfixtu ...

Utilizing React-Router-Redux alongside the powerful features of React-Bootstrap

I've been struggling with this issue for some time now! My goal is to create a 'main app container' that consistently displays the logo, navigation... I plan on using react-bootstrap to enhance its appearance. Currently, I'm encounter ...

Leveraging the concealed input value during an AJAX operation following its configuration

I'm encountering an issue with a command button that sends browser information to a backing bean using Javascript and AJAX. Despite setting the hidden input value correctly on click, the data is not available during the first execution of the action. ...

Obtaining the Immediate ID of a Widget using JQuery

I currently have the following setup: <div id="dualList"></div> I created a plugin but stripped it down for testing purposes. I am encountering difficulties with the plugin not displaying the ID of the div. <script> (function($) { ...

The shade of grey on the curve appears instead of the usual red on the iPad. Any ideas on how to fix

I am having trouble creating a curve like the one shown below on my iPad. The color appears to be gray and does not work properly. Is this a bug with ChartJS or is there a solution to fix this issue? This problem occurs when the type value is set to "lin ...

When the mouse hovers over the image within the div, it undergo

I want to create "links" that are actually titles of equipment or items I wish to review. When the title is moused over, I want the image to change, but remain changed even after the mouse moves away. Existing code options don't meet my requirements. ...

What is causing the CSS transition to fail in the updated DOM?

When attempting to apply a CSS transition as shown in the following code snippet: https://jsfiddle.net/sunyuu/e58sfeva/17/ var Main = { data () { return { isActive: false, childStyle: {} }; }, methods: { sho ...

Ways to incorporate additional values into an array object with Vuex

I'm new to using vuex and I am attempting to save objects into an array called orders within the store.js file. My goal is to extract values from an object (such as me.title) and save them into an array within the store file by clicking on a button t ...

Using jQuery to append an <option> element to a <select> tag

Every time I try to add an option to a select, the option I want to add gets appended to the first option instead of the actual select element. $(".ct [value='']").each(function() { $(this).append($("<option></option>").attr("val ...

what is the duration for which a browser stores an ajax response in cache

How can I determine the duration for which a browser caches an ajax response? In Chrome's dev tools network tab, I see that the resource is retrieved from disk cache. Is there a way to know the expiration time of this cached data? The resource being ...

Can Nuxt's asyncData handle multiple requests with conditional statements?

I've been grappling with this issue for some time now. I understand how Nuxt asyncData can be used to make either one request or multiple requests, but is there a way to incorporate conditional logic for making multiple requests based on a query param ...

Encountering a 500 error when using Ajax in Laravel

Encountering error 500 in network while attempting to add data to the database using ajax. Error Codes AJAX <script> $( document ).ready( function() { $("#modalsave1").click(function(e){ e.preventDefault(); $.ajax({ type: "po ...

A similar functionality to the async pipe in TypeScript

In my Ionic2 project, I'm utilizing ng-translate from ng2-translate to translate strings in the code. Currently, I am using the service in the following way: translate.get('ERROR').subscribe((res: string) => { //The translated string ...