Sweet Alert confirmation before delete

Sweet Alert confirmation before delete

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Sweet Alert confirmation before delete

When building interactive forms, relying on native browser alerts (alert()) for destructive actions is a common frustration. Developers often upgrade to SweetAlert2 to improve the visual experience and provide better user feedback. However, integrating these modern UI libraries with traditional server-side processing requires careful attention to execution order. A frequent point of failure occurs when the client-side JavaScript executes immediately upon clicking a button, bypassing any confirmation logic you've defined.

In the scenario presented by the original code, the issue stems from how the HTML form handles the submit event versus how SweetAlert2 is initialized. The core problem is that the browser processes the form submission synchronously before allowing JavaScript events to fully resolve in certain contexts, or more accurately in this specific case, the confirmation dialog is being triggered, but the subsequent action logic needs to be decoupled from the immediate page reload flow if you want a cleaner user experience.

Looking closely at the provided HTML:

<button class="btn btn-danger" type="submit" name="archive" onclick="archiveFunction()">
    <i class="fa fa-archive"></i>
        Archive
</button>

The onclick="archiveFunction()" attribute is attached directly to the form submit button. When a user clicks this, two things happen nearly simultaneously: the browser attempts to submit the POST request defined in the <form> tag, and the JavaScript function archiveFunction() is invoked.

While SweetAlert2 does pause execution until a choice is made (via its internal promise handling), there is a critical mismatch between where the confirmation happens and where the data is actually deleted. In the PHP code provided:

if(isset($_POST['archive']))
{
    $p_id = $_REQUEST['p_id'];
    // sql to delete a record
    $sqli = "UPDATE students SET archive = 2 WHERE p_id=$p_id";

    if ($conn->query($sqli) === TRUE) {
        echo "swal('Archived!', 'Click ok to see!', 'success')";
    } else {
        echo "Error Archiving record: " . $conn->error;
    }

    $conn->close(); 
}

The server-side logic checks for the archive POST variable and executes the SQL update immediately. If the form submits successfully, the browser navigates to the result page (or reloads the current page) before the SweetAlert promise fully resolves or if the developer expects a redirect after the alert.

The specific complaint in the source material—that the file deletes without the confirmation popping up—often indicates that the onclick handler is firing, but the form submission happens so fast that the user perceives an immediate deletion, especially if the server response is cached or if the client-side code isn't handling the promise correctly before the page refreshes.

To fix this, you must separate the confirmation logic from the direct form submission mechanism. The most robust pattern involves preventing the default form submission in the JavaScript event handler until the user has interacted with the SweetAlert dialog. This ensures that no data is sent to the server until the user explicitly confirms the action.

Here is how you should restructure the approach:

  1. Remove onclick from the button: Do not trigger the deletion logic or show alerts directly on the form submit button.
  2. Prevent Default Submission: Inside your JavaScript function, call event.preventDefault() before showing the SweetAlert dialog. This stops the browser from sending the POST request immediately upon clicking.
  3. Handle the Promise: SweetAlert returns a promise when you use callbacks or then. You need to resolve this promise before allowing the form to submit if you want to handle the success message on the client side, or redirect only after confirmation.

Revised JavaScript logic would look like this:

function archiveFunction(event) {
    // Prevent the form from submitting immediately
    event.preventDefault();

    const pId = document.getElementById('p_id').value;

    swal({
        title: "Are you sure?",
        text: "But you will still be able to retrieve this file.",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes, archive it!",
        cancelButtonText: "No, cancel please!",
        closeOnConfirm: false,
        closeOnCancel: false
    }, function(isConfirm) {
        if (isConfirm) {
            // Only now do we submit the form or redirect
            // You can either manually dispatch a custom event or let SweetAlert handle the redirect
            document.getElementById('archiveForm').submit(); 
        } else {
            swal("Cancelled", "Your imaginary file is safe :)", "error");
        }
    });
}

// Attach to the button without preventing default here
document.querySelector('button[name="archive"]').addEventListener('click', archiveFunction);

By deferring the actual form submission until after isConfirm is true, you guarantee that the SQL query only executes when the user clicks "Yes". This eliminates the race condition where the server processes a request before the user has had a chance to read the warning message. If you are using Laravel or similar frameworks where redirects are preferred after success, you can return a redirect response from your controller instead of echoing raw HTML, ensuring a cleaner separation of concerns.

Our network