How can AJAX be used in PHP to achieve the desired functionality of automatically reloading the index.php page after deleting an image?

To achieve the desired functionality of automatically reloading the index.php page after deleting an image, AJAX can be used in PHP. This involves sending an AJAX request to the server to delete the image, and then using JavaScript to reload the page upon successful deletion.

<?php
// Check if the image deletion request is received
if(isset($_POST['delete_image'])) {
    // Code to delete the image from the server

    // Send a response back to the client
    echo "Image deleted successfully";
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Delete Image</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <button id="deleteBtn">Delete Image</button>

    <script>
        $(document).ready(function() {
            $('#deleteBtn').click(function() {
                $.ajax({
                    url: 'index.php',
                    type: 'POST',
                    data: { delete_image: true },
                    success: function(response) {
                        alert(response); // Display success message
                        location.reload(); // Reload the page
                    },
                    error: function() {
                        alert('Error deleting image');
                    }
                });
            });
        });
    </script>
</body>
</html>