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

Express js routing issue ("Page Not Found")

Why do I receive a "Cannot GET /" message when I access my HTTP server at http://localhost:8000/? I am using Express JS for server-side routing and Angular for client-side. Some sources suggest that this error occurs because I haven't set a route for ...

Guide on integrating the @nuxtjs/axios plugin with Nuxt3

I'm trying to fetch API data from using this code: <template> <div> </div> </template> <script> definePageMeta({ layout: "products" }) export default { data () { return { data: &apo ...

Is there a way to select and handle multiple elements using async wdio with the same selector?

My test scenario involves using async wdio to test my React app, where I need to count elements with a specific selector and check their contents. The code snippet being tested is as follows: <div className='container'> <li className= ...

Learn the process of implementing an SVG icon in your Angular Material project

I'm currently attempting to incorporate a single icon into my Angular Material application. Following the documentation, I have implemented $mdIconProvider in the following manner: app.config(function($stateProvider, $urlRouterProvider, $mdIconProvid ...

You cannot nest a map function within another map function in React

Having some trouble applying the map function in HTML using React. Below is the code snippet: response = [ data : { name: 'john', title: 'john doe', images: { slider: { desktop: 'link1', mo ...

What is the best way to distinguish if users are accessing my Facebook app through an iframe or by directly entering the

If my Twitter app url is http://tw.domain.com/ and the app url is http://apps.twitter.com/demoapp/ I need to ensure that users cannot access the application url directly, they must view it within an iframe on Twitter. What method can I use to detect & ...

The Redux store is duplicating the state across different reducers, causing it to appear twice

Having Trouble Viewing Different States for Two Reducers in Redux DevTools In my React project, I am attempting to incorporate a second reducer using Redux to gain a better understanding of the overall state. However, when I inspect the state in Redux Dev ...

What are the steps to designing customizable drop-down content menus on websites?

I am looking to implement a feature where I can create content drop-down bars similar to the ones shown in the images. When a user clicks on the bar, the content should be displayed, and if clicked again, the drop-down should hide. I have searched for a so ...

What is the best method for setting up message scheduling for a Microsoft Teams bot based on different time

I am trying to figure out how to send messages to users from my bot at specific time intervals. Currently, I'm using agenda for scheduling messages, but I've run into an issue with the timezone discrepancy - agenda is 5:30 hours behind my timezon ...

What is the best way to include multiple entries in a select2 form using ajaxform?

select2/3.5.2/ I had to repost this because my initial post was not formatting correctly. The tools in use are: A select2 form field that allows searching through multiple records A bootstrap popup modal containing a form for entering a new record if i ...

Code snippets to reduce excess white space on a website using HTML and CSS

On my website, there are multiple tabs, each containing content from an HTML file. When a user clicks on Tab1, boxes with images are displayed. The layout can be seen in the following Code Demo: Code Demo here There seems to be extra space before and afte ...

Using the power of node.js to iterate through a loop of queries and execute

While I am running a for loop, within the loop itself I am executing a PostgreSQL query and storing the result in an array. However, I am unable to determine the order of execution. Here is my code: var array =[]; for(var i = 0 ; i< latitude.le ...

Type of JavaScript map object

While exploring TypeScript Corday, I came across the following declaration: books : { [isbn:string]:Book}={}; My interpretation is that this could be defining a map (or dictionary) data type that stores key-value pairs of an ISBN number and its correspon ...

The method of AJAX Pattern for users to make interactive decisions

Currently, I am exploring different strategies to create interactive user decisions. My project involves a rather extensive form that users need to fill out. Upon submission, an AJAX-Post-Request is transmitted to the server. While some fault checks can be ...

Implementing Vue.js functionality to dynamically add or remove values from an array based on the state of a checkbox

I recently embarked on my journey to learn vue.js and I've encountered a challenging issue. I have dynamic data that I render using a 'v-for' loop. Additionally, I have an empty array where I need to store checked checkbox data and remove it ...

"Unraveling the depths of a multidimensional array in JavaScript: a comprehensive guide

Seeking assistance from this wonderfully helpful community :) It seems like I might be declaring and creating my arrays incorrectly, as I am trying to add content to an array of arrays but unable to retrieve anything from it. Here's the code snippet ...

Unable to assign a scroll event delegation by using the "on" method

When attempting to delegate a scroll event in order for my element to maintain the same handler after being returned by an ajax call, I utilized the on method for delegation. $('body').on({ scroll:function(){ alert('scrolling&ap ...

Verify the level of opacity in the image

I'm working on a website that allows users to upload PNG images and save them. However, before they can save the image, I need to check if it contains transparency. Is there a way to determine if an image is not 24-bit using JavaScript? <img id= ...

PHP: How to target a specific JSON array and properly append POST data?

Iā€™m dealing with a JSON file that looks like this: [{ "name": "James", "reviews": [ { "stars": 5, "body": "great!" }, { "stars": 1, "body": "bad!" } ] }, { " ...

Generating a JavaScript object from a string to optimize its compatibility with datatables

This inquiry pertains to the plugin available at: var hidecols = '{"sClass": "Hide", "aTargets": [0]},{"sClass": "asdf", "aTargets": [1]},{"sClass": "qwer", "aTargets": [2]}'; var hidecolsobj = eval('(' + hidecols + ')'); ...