I'm experiencing issues with my AJAX as it fails to post or respond after the user clicks on the submit

I am currently working on implementing a list of events, each with a tick box and an x box for marking the event as complete or deleted. The challenge I'm facing is that when I click the buttons, nothing happens without refreshing the page.

I suspect that the issue stems from having multiple event boxes that are not properly identified as unique. I need to ensure that the right event is updated in the database, but I'm unsure how to make this distinction since my files only contain queries. Additionally, the data is not being posted at all when the button is clicked.

HTML/PHP

<div class="w3-card w3-round w3-white w3-center delete_mem">
    <div class="w3-container">
        <p>Upcoming Event</p>
        <span><?= $appRow['customer_appointments_type']; ?></span>
        <p><?= $appRow['customer_appointments_datetime']; ?></p>
        <div class="w3-row w3-opacity">
            <div class="w3-half">
                <a id="<?= $appRow['customer_appointments_id']; ?>" class='w3-button w3-block w3-green w3-section btn-good'><i class='fa fa-check'></i></a>
            </div>
            <div class="w3-half">
                <a id="<?= $appRow['customer_appointments_id']; ?>" class='w3-button w3-block w3-red w3-section btn-danger'><i class='fa fa-remove'></i></a>
            </div>
        </div>
    </div>
</div>

Javascript/AJAX

$(document).ready(function() {
    $('.btn-danger').click(function() {
        var id = $(this).attr("id");
        if (confirm("Are you sure you want to delete this appointment?")) {
            $.ajax({
                type: "POST",
                url: "scripts/lead/deleteLeadTask.php",
                data: ({
                    id: id
                }),
                cache: false,
                success: function(html) {
                    $(".delete_mem" + id).fadeOut('slow');
                }
            });
        } else {
            return false;
        }
    });

    $('.btn-good').click(function() {
        var id = $(this).attr("id");
        if (confirm("Are you sure you want to complete this appointment?")) {
            $.ajax({
                type: "POST",
                url: "scripts/lead/completeLeadTask.php",
                data: ({
                    id: id
                }),
                cache: false,
                success: function(html) {
                    $(".delete_mem" + id).fadeOut('slow');
                }
            });
        } else {
            return false;
        }
    });
});

Answer №1

It's important to avoid using the same ID for different elements in your code, as you mentioned. Modify your code to look something similar to this:

HTML

<button type="button" onClick='delete(<?= $appRow['customer_appointments_id']; ?>)' class='w3-button w3-block w3-red w3-section btn-danger'><i class='fa fa-remove'></i></button>

Next, create a JavaScript function that will execute when the delete button is clicked:

Javascript

function delete(id){
if (confirm("Are you sure you want to delete this appointment?")) {
      $.ajax({
         type: "POST",
         url: "scripts/lead/deleteLeadTask.php",
         data: ({
             id: id
         }),
         cache: false,
         success: function(html) {
            $(".delete_mem" + id).fadeOut('slow');
         }
     });
  } else {
      return false;
    }
}

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

Tips for configuring the delay of AJAX loading

Here is my code snippet: I am facing an issue where the data is being loaded multiple times when I scroll to the end of the page. Let's say there are 10 elements on the page and I load data from "/api/get_more_application/10". However, before the load ...

Applying a class change in Vue.js upon mounting

How can I make a button element with a .hover property trigger the hover animation as soon as the page loads? I want to apply a class to the button when the page is mounted and then remove it later. What is the best approach for this? I considered using a ...

Assist in troubleshooting and pinpointing the solution to this issue

function generateRandomString(length) { var result = ""; var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"; var charactersLength = characters.length; for (var i = 0; i < length; i++) { result += characters ...

Inline CSS for altering the appearance of text within a DIV container

Within the confines of this DIV element... <div name="layer1" style="background-color:lightblue;"> <hr>Site:Downtown DataCenter Device: 2KBS</hr> </div> Hello there, I am utilizing Inline CSS Styling. Is it possible to make the t ...

Resetting the randomness in a function within a sudoku generator implemented in JavaScript

I'm in the process of creating a unique Sudoku generator that incorporates randomness into its design. Within my code, there's a particular function responsible for generating the Sudoku puzzles. The issue I'm encountering is the inability t ...

Can a specific element be chosen based on its background color?

Is it possible to change the background color of a child element within a div that has a specific background color using CSS? See my explanation below. For example: .container[background-color=some color] .content { background-color: some other color ...

Ensuring the Jquery Datepicker restricts selecting dates later than or equal to the start date (

I have a specific requirement where I need to implement two date pickers for entering "From" and "To" dates. The "ToDate" selected should be greater than or equal to the "FromDate" (after selecting a from date, all previous dates should be disabled in the ...

Having trouble connecting to my MongoDB container using Node.js

I am facing an issue while trying to connect my local mongoDB docker, named "some-mongo", to my NodeJS backend server running on the same computer. The problem arises when attempting to establish the connection using the "mongoose" module. To launch my mo ...

What is the best way to create a loop within a JavaScript function?

I'm having some trouble with looping inside a function. It seems like my looping is not working properly and I need help fixing it, along with suggestions for the problem. :) Here's what I've tried: <script> function getImage1( ...

What is the best way to structure my POST data when conducting tests on an express API endpoint?

I have been exploring the MERN stack with the help of this guide: https://www.digitalocean.com/community/tutorials/getting-started-with-the-mern-stack. Currently, I am trying to test a POST API endpoint that is built using express. The node server is up ...

Cropped portion of the captcha image located on the left side

edit: I manually adjusted cnv.width = this.width to 120 and it seems to be working. Upon closer inspection, I discovered that the image has both a rendered size and an intrinsic size. The width is 35 for rendered size and 40 for intrinsic size, which may e ...

The intersection observer fails to detect any new elements or entries that are appended to the page after it has

When I press the "add section" button to create a new section, the intersection observer does not seem to observe it. Even when I try to run the observer again after pressing the button, it still doesn't work. I suspect that I need to reassign the `se ...

Position a div element after another using the :after pseudo-element

My goal is simple to explain, but I have exhausted all my efforts trying to achieve it. I am hoping for the ★ symbol to appear immediately after the number 06 using jQuery. Any assistance would be greatly appreciated. The numbers are generated by a s ...

Obtaining data objects with Angular 2 from JSON

Recently, I received a URL that includes data arrays in JSON format. My goal is to retrieve and utilize all elements within it: However, when attempting this, I end up with everything but nothing specific. For instance: How can I access data.name or data. ...

What is the method for converting this pattern into a JavaScript regex?

This code is functioning properly newRow.replace('[[' + key + ']]', item); I attempted to use regex for the replacement, but it is not working as expected newRow.replace('/\[\[' + key + '\]\]/' ...

Which data types in JavaScript have a built-in toString() method?

Positives: 'world'.toString() // "world" const example = {} example.toString() // "[object Object]" Negatives: true.toString() // throws TypeError false.toString() // throws TypeError Do you know of any other data types that wi ...

Iterating through two classes in a Javascript loop

Hello, I'm facing a small obstacle that I'm hoping to overcome using JavaScript/jquery. Essentially, I have multiple div classes and I want to create a loop that adds a class to specific divs without manually assigning an id to each one. The goal ...

Using the `ssh2` module in Node.js without specifying a specific object

When you use require('ssh2') in Node.js without a specific object (e.g. require('ssh2').Client), what does it imply? I'm in the process of understanding some code and still new to learning Node.js. Here's how it is being used: ...

Looking for giphy link within a v-for loop (Vue.js)

I am fetching a list of movie characters from my backend using axios and rendering them in Bootstrap cards. My objective is to search for the character's name on Giphy and use the obtained URL as the image source for each card. However, when I attemp ...

Experiencing difficulties with incorporating cURL data into MySQL using Simple Dom Parser

Hey there! I'm currently trying to figure out the best way to save my scraped data to a MySQL database. It seems like nothing is getting inserted into the database, and I suspect it might be due to the format of the data I'm passing. Should I con ...