Skip to content

Confirm button before running deleting routine from website

Yes, you can add a confirm button before running a delete routine on a website using PHP. Here is an example of how this can be done:

  1. Create a delete button that, when clicked, will trigger the delete routine. For example, you can create a button with the text "Delete" and an id of "delete_button".

Example of creating a button with the text "Delete" and an id of "delete_button"

html
<button id="delete_button">Delete</button>
  1. Use JavaScript to attach an event listener to the delete button. When the button is clicked, the event listener will display a confirm dialog box asking the user to confirm or cancel the delete action. Include jQuery for the AJAX call, then handle the confirmation and request.

Example of using JavaScript to attach an event listener to the delete button

html
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
javascript
document.getElementById("delete_button").addEventListener("click", function(event){
    event.preventDefault();
    if(confirm("Are you sure you want to delete this item?")){
        $.ajax({
            url: "delete_script.php",
            type: "post",
            data: { id: 1 }, // Replace with actual item ID
            success: function(response) {
                if(response == "success"){
                    // Do something like removing the item from the page
                }
            }
        });
    }
});
  1. In the PHP script, you can use the received id to delete the item from the database. Ensure you validate the input and handle errors securely.

Example of using the received id to delete the item from the database in PHP

php
<?php
$id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
if (!$id) {
    echo "error";
    exit;
}

// Use PDO with prepared statements for security
// Replace placeholders with your actual database credentials
$pdo = new PDO('mysql:host=localhost;dbname=your_db', 'your_username', 'your_password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

try {
    $stmt = $pdo->prepare('DELETE FROM items WHERE id = :id');
    $stmt->execute(['id' => $id]);
    echo "success";
} catch (PDOException $e) {
    echo "error";
}
?>

This is a basic example and can be modified to fit the specific requirements of your website.

Dual-run preview — compare with live Symfony routes.