Ensure confirmation dialog box pops up multiple times when deleting an item using AJAX

On my website, I have a side menu with multiple navigation items. In the admin section, there is a table where I can manage these items. The issue arises when I delete an item from the table using ajax - it gets deleted from both the table and the side menu. I used the load function to refresh the items in the menu. However, if I delete multiple items, I end up getting multiple confirmation pop-ups based on the number of elements removed.

https://i.sstatic.net/NgJRK.png Take a look at the image for reference. When I click on the delete button, the item is removed from the database and the table. Deleting the first item triggers a single confirm pop-up as expected. But subsequent deletions result in multiple pop-ups appearing. Where could I be going wrong here?

Menu Code:

echo '<div id="slide-out" class="side-nav sn-bg-4 fixed mdb-sidenav">
            <ul id="menu_ul" class="custom-scrollbar list-unstyled" style="max-height:100vh;">
                <!-- Side navigation links -->
                <li>
                    <ul id="side-menu" class="collapsible collapsible-accordion">
                    <li id="home" class="menu-item menu-item-type-custom menu-item-object-custom"><a class="collapsible-header waves-effect" href="/admin/view/main.php"><img src="/imgs/icones/ic_home.png">Home</a></li>';

    foreach ($Menu_array as $valor)
    {

        echo '<li id='. $valor->getCategoria()->getCat_id() .' class="menu-item menu-item-type-custom menu-item-object-custom'. $menu_filhos .'"><a class="collapsible-header waves-effect '"><img style="margin-right:10px; vertical-align: text-bottom; text-align:left" src="'.$valor->getCategoria()->getCat_img().'">'. $valor->getCategoria()->getCat_nome().'</a>';

            $array_SCat = [];
            $array_SCat = $valor->getlist_SCat();

            if((count($valor->getlist_SCat())) > 0)
            {
                echo '<div class="collapsible-body">
                        <ul class="sub-menu">';

                foreach($array_SCat as $val)
                {
                    echo '<li class="menu-item menu-item-type-post_type menu-item-object-page '"><a class="collapsible-header waves-effect" id='.$val->getSCat_id().' href="'.$variaveis->getDominio().'/'.$variaveis->getNome_site().'/admin/view/ld.php?id_cat='.$valor->getCategoria()->getCat_id().'&id_subcat='.$val->getSCat_id().'">'.$val->getSCat_nome().'</a></li>';
                }
                    </ul>
                </div>';
            }
        }
    }
        echo '</ul>
        </li>
        <!-- /. Side navigation links -->
        </ul>
    </div>';

The table code for deleting an item:

<table width="100%">
    <tbody>
         <tr>
              <td><a id="deleteItem" name="'.$val->getSCat_id().'">Delete</a></td>
         </tr>

Ajax code:

$(document).on("click", "#deleteItem", function(e) {

    e.preventDefault();

    var idItem = $(this).attr('name');
    var $tr = $(this).closest('tr');

    if (confirm('Do you want to delete this item?')) {

        $.ajax({
            url: '/admin/control/ajax/remove.php',
            type: 'POST',
            data: {id: idItem},
            dataType: 'html',
            success: function(response) {

                var result = $.trim(response);

                if(result === "success") {

                    $tr.find('td').fadeOut(800,function(){ 
                        $tr.remove();
                    });

                    $("body").load('#slide-out');

                } else if(result === "error") {

                    alert("Error.");

                }

            }

        });

    }

});

Note that I included this line in ajax:

$("body").load('#slide-out');

This allows the body to call and load the menu with the ID slide-out.

Answer №1

Consider updating the attribute id to a class named "deleteItem". Here are the locations where changes need to be made:

HTML Markup

<td><a class="deleteItem">Delete</a></td>

Javascript

$(document).on("click", ".deleteItem", function(e) {});

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

Tidying up JQuery with automatic selection of the next div and navigation item

My primary question revolves around optimizing the code for a functionality where clicking on 5 images reveals a related div while hiding the rest. As a newcomer to jQuery, I feel that my current implementation is somewhat messy and lengthy. Seeking advice ...

Improving user experience with CodeIgniter's form validation powered by AJAX and jQuery

I am currently attempting to validate certain fields using AJAX in CodeIgniter, but I'm having some difficulty getting it to work correctly. This is the AJAX code snippet that I have: var timeout = null; $(document).ready(function(){ $('. ...

What could be the significance behind these sudden pop-ups of console error messages?

var sendTitle = function() { var title = $("input[name='movie-search-title']").val(); getMovie(title) getQuotes(title) } $("input[name='movie-search-title']").keydown(function(e) { if (e.keyCode == 13) { e.preventDefault(); ...

Guide to handling URL errors in a form using AngularJS

I'm currently working on implementing URL validation for my form. The validation itself is working properly, but I've encountered an issue. Previously, I had validation set up so that an error message would display when submitting the form with e ...

Retrieving the length of a Pipe in the parent component using Angular 2

In Angular2, I have created a custom pipe to filter an array based on type ID and year arrays. Here is how it is defined: @Pipe({name: 'highlightedWorksFilter', pure: false}) export class HighlightedWorksFilterPipe implements PipeTransform { tra ...

I would like to give the option for file uploads, but the form refuses to submit unless a file is uploaded

I've recently developed a form in React and React Bootstrap, and I've encountered an issue with the file upload feature. I want the file upload to be optional, but when I try to submit the form without uploading a file, it doesn't work as ex ...

Access information from JSON file

Looking to extract data from an external JSON file and store it in a JavaScript array for manipulation? Here is a snippet of the JSON file for reference: "Country":[ { "Country_Name":"India", "Country_Details":[ { ...

Utilize CSS properties to pass as arguments to a JavaScript function

Is there a way for me to make my CSS animation functions more efficient? I have similar functions for different properties like height, width, and left. Can I modify the function below to accept a CSS property argument instead of hardcoding height? Window ...

Utilize D3's pie chart to showcase the data in JSON's individual collections

I am currently working on creating a pie chart that displays the distribution of collections based on their names. I have come across an issue where d3.layout.pie().value() only evaluates specified array values. Is there a solution available to extract the ...

Do arrays permanently retain the strings stored within them?

As an 11-year-old who has been learning Javascript for the past month and a half, I am currently working on creating a login/register system. Right now, my focus is on the register part. I have a question: when adding a string/number/boolean to an array, d ...

Ensure that the input box expands to occupy the entire HTML page

After reviewing numerous pages and questions related to this topic, I have located the correct solution but am struggling to implement it. My goal is to achieve a similar outcome to the second question, but I'm having difficulty figuring out how to do ...

Issues encountered when incorporating personalized CSS into a Vuetify element

Working with the Vuetify selector input component, v-select, and wanting to customize its style led me to inspecting it in Chrome and copying down the necessary classes. For instance, to change the font size of the active value, I utilized: .v-select__sel ...

Generating a JSON object based on the selection of dynamic checkboxes

Hello everyone, I am new to jQuery so please be patient with me as I embark on this journey! My goal is to structure my data in the following format... { "qualifications": [ "1", "7" ], units: [ "7", "3", "1" ] } The HTML looks like ...

What are the steps to viewing an image or video file in full screen mode on a web browser?

Is there a way to play video/image files in full screen mode on a browser? How can I achieve this? ...

Having trouble iterating over the JSON data received from an AJAX call

My code is returning a JSON object stored in a variable called data [ {"Id": 10004, "HEAD_NAME": "avcc"}, {"Id": 10040, "HEAD_NAME": "tyiiio jj"}, {"Id": 10059, "HEAD_NAME": "errr"} ] I'm attempting to iterate through the collection us ...

Showing list data from script to template in vue - A step-by-step guide

My task involves displaying data from the main table in MySQL. I need to show the type of each major by comparing it with the id in the faculty table. I have successfully logged this information using console.log, but I'm unsure how to display it on t ...

HTML5 Mouse Canvas

Here's a simple example of what's happening: function handleClick(event) { ... } canvas.addEventListener("click", handleClick, false); function drawRectangle(x, y) { context.fillRect(x, y, 16, 16); }; ...

Considerations for Developing an AJAX-Powered Web Application

We are currently embarking on developing an AJAX-based web application that will involve exchanging information and generated HTML using JSON/POST techniques. Thanks to a cache layer incorporating memcached and disk-based caching, we can efficiently retrie ...

is there a way to modify the background color of a div element by comparing values in javascript?

Is there a way to dynamically update the background color of a div element within a table based on values stored in a json array from a database? ...

Is it possible to store a JWT token in local storage when working with Next.js?

We are considering using Next.js for our application, with a focus on client-side rendering for data fetching. The API we will be interacting with is external and requires authentication to access specific user dashboard content. While the homepage will ...