Ruby application requires refreshing for Ajax deletions to take effect

I am currently working on developing a task management app using Rails. Each to-do list in the app contains multiple tasks, and my issue lies in deleting a completed task with Ajax without having to manually refresh the page for it to vanish. As I am still new to Rails and Javascript, any advice or suggestions would be highly appreciated.

Below is the code snippet from my Items destroy Javascript file:

<% if @item.destroyed? %>
$('#item-' +<%= @item.id %>).hide();
<% else %>
$('#item-' +<%= @item.id %>).prepend("<div class='alert alert-danger'><%= flash[:error] %></div>");
<% end %>

The following code is from the Lists#show view which calls the item partial:

%h1= @title
.row
  .col-md-6
    = render 'items/item', locals: {items: @items}
.row
  .col-md-6
    = render 'items/form', locals: {list: @list, item: @item}

= link_to "Edit", edit_list_path(@list), class: 'btn btn-success'

= link_to "Delete List", @list, method: :delete, class: 'btn btn-danger', data: { confirm: 'Are you sure you want to delete this to-do list?' }

- if @lists.nil?
  = link_to "New To-do List", new_list_path, class: 'btn btn-success'

The Item partial section is as follows:

- @items.each do |item|
  = item.name
  = link_to "", [item.list, item], method: :delete, class: 'glyphicon glyphicon-ok', remote: true
  %br/

This is the implementation in the Items Controller:

class ItemsController < ApplicationController
  respond_to :html, :js

  def create
    @list = List.find(params[:list_id])
    @item = @list.items.new(item_params)
    @item.user_id = current_user.id
    if @item.save
      redirect_to @list, notice: 'Your new To-Do Item was saved!'
    else
      redirect_to @list, notice: 'You forgot to enter a To-Do item. Please try again.'
    end
  end

  def destroy
    @list = current_user.lists.find(params[:list_id])
    @item = @list.items.find(params[:id])
    @title = @list.title

    if @item.destroy
      flash[:notice] = "\"#{@item.name}\" was deleted successfully."
    else
      flash[:error] = "There was an error deleting the list."
    end

    respond_with(@item) do |format|
      format.html {render [@list]}
    end
  end

  def item_params
    params.require(:item).permit(:name)
  end
end

Answer №1

After your app sends a delete request triggered by clicking the link generated by

= link_to "", [item.list, item], method: :delete, class: 'glyphicon glyphicon-ok', remote: true
, the view remains unchanged. In order to hide the item element upon a successful ajax delete request, you must implement an event listener.

Below is a basic code snippet to help you achieve this functionality. Please note that the code has not been tested, but it should give you a general idea of how to proceed.

Item Partial:

.item-container
  - @items.each do |item|
    .item
      = item.name
      = link_to "", [item.list, item], method: :delete, class: 'glyphicon glyphicon-ok', remote: true

JS:

$(document).ready(function() {
  $('.item-container').on('ajax:success', function() {
    $(this).closest('.item').hide();
  });
};

References:

Lastly, make sure to properly integrate the JavaScript code you've shared into your application for it to be executed accordingly.

Answer №2

While I'm not an expert in HAML, it appears that you may be missing an ID in your view file. Your script destroy.js.erb is searching for a selector such as id=item-1 to hide the item. Therefore, you should ensure that each item in your partial has a unique ID assigned to it. In ERB syntax, this could be achieved with the following code:

<ul>
<% @items.each do |item| %>
  <li id="item-" + item.id><%= item.name %> </li>
<% end %>
</ul>

Hope this helps clarify things for you :)

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

Remove the click event once the sorting process has been completed

I am currently working on a project that involves creating a list of sortable images using jquery sortable. Users can easily drag and drop the images for sorting purposes. Additionally, each image's parent anchor has a click event attached to open it ...

jQuery: changing the order of list elements with the eq method

I've been tackling a challenge with designing a navigation bar that consists of 3 items. The goal is to have the clicked item move to the center position on the horizontal navbar while re-arranging the order. Here's the code snippet I've com ...

What to do when CSS Overflow doesn't work as expected?

Are there any alternatives for browsers that don't support CSS overflow? I am working on a new layout that heavily relies on the overflow property, however it seems like android browsers do not handle it well and as a result, my layout is broken. I am ...

Encountered an error while trying to click the cookie button using Selenium: "object[] does not have a size or

I've been struggling to interact with a button inside a pop-up using Selenium, but I keep encountering this error: object [HTMLDivElement] has no size and location I initially tried to simply click the button since it is visible on the page and I wai ...

Can you tell me which specific font Adobe Edge Code (Brackets) uses in its code editor?

Can someone please help me? I'm trying to identify the syntax highlighter being used in this code. Is it Prettify or something else? ...

The program encountered an unexpected identifier 'getProject' instead of ';'. It was expecting to find a semicolon after the async variable declaration

When using this JavaScript on a webpage, I encounter an issue: <script async type="module"> import {projectCode} from "./assets/js/config.js"; import {getProject} from "./assets/js/saleproject.js"; import {getAccount} fr ...

Tips for adjusting the language settings on a date picker

Is there a way to change the language from English to French when selecting a month? I believe I need to configure something in the core.module.ts. How can I achieve this? https://i.sstatic.net/Cpl08.png @NgModule({ declarations: [], imports: [ Co ...

Web Page Content Scrambling/Character Exchange

I've encountered a perplexing issue that seems to strike randomly, yet I've managed to replicate the problem on three different desktops. Oddly enough, some other desktops never experience this issue and I'm at a loss as to what could be cau ...

Can you tell me the specific parameter used in the beforeSend function in jQuery?

I have been examining some instances of the beforeSend callback function. Sometimes, these examples include an input parameter: beforeSend:function(req) or beforeSend:function(xhr). I assume that this parameter represents the XMLHTTPRequest of the jquery ...

Unleashing the power of Vuex with promise chaining

One challenge I am facing is making API calls to retrieve an array of endpoints, which are then used to fetch data from another API. // Raise isLoading flag this.$store.commit('isLoading', true); // Initial data fetch this.$s ...

If the element is checked and equal to a specific value, take action

I am trying to hide one of the 3 radio buttons on my page. Although they all have the same class, each button has a different value. I attempted to write code to achieve this, but unfortunately, it is hiding all radio buttons instead of just one. Could s ...

The difference between `$(document)` and `$("document")` is like night

Does a distinction exist between: $(document) and $("document")? ADJUSTMENT: also when using the .ready() method like $("document").ready() ...

Employing VAutocomplete component from vuetify in combination with a render function (scoped slot)

Trying to implement the Autocomplete component within a render function but encountering issues with the scopedSlots feature. Here is my code snippet: import { VAutocomplete } from 'vuetify/lib' export default { render (h) { return ...

Obtaining the most up-to-date information using unique column value - utilizing mongoid and rails4

Within my MongoDB database, I have a collection called kevent that has entries structured like so: _id, user_id action created_at 43gy5235rwedwe 11 logout 2014-05-30 04:01:32 +0000 563gy5wwwedwex 11 ...

Best practices for outputting objects within an array using jQuery and JavaScript

Seeking guidance. I am utilizing a unique jQuery calendar plugin (which appears to be uncommon!) that is fully initialized with JS, without any HTML. In order to include events, you must define each event as an object inside an array: events: [ { ...

Properly accessing a JavaScript object acquired from a JSON file

I have a JSON file with data for 4 different items. Once I parse the JSON file, I see the output below. At that point, do I now have a JavaScript object? My goal is to access each item and add them to a plain object. How can I achieve this? The resulting ...

Include a personalized header in $http

In my factory, I have multiple functions that follow this structure: doFunction: function () { return $http({ method: 'POST', url: 'https://localhost:8000/test', data: {}, headers: { "My_Header" ...

Form a hierarchical data structure using a combination of three arrays

Here are three sets of data: let firstData = [ {key: value1}, {key: value2}, {key:value3} ] let secondData = [ {key: value1}, {key: value2}, {key:value3}, {key: value4} ] //same structure, different values let thirdData = [ [1,1,1,1], [1,1,1,1], [1,1,1,1] ...

Select an image based on the input value provided

I'm new to coding and I'm attempting to replicate the search functionality of icomoon where typing a word displays related images. However, I'm facing an issue where I can't seem to get the value entered in the input field to trigger an ...

Displaying the combined total for each date

My goal is to calculate the total for each department without duplicates ( which is currently working ) and display all results based on the selected date. I intend to select a date using md-datepicker and then only display the total task time where the d ...