javascriptphpfunctionsweetalert

How to execute a PHP script upon SweetAlert2 confirmation?


I use Sweet Alert 2 for nice dialogs.

Now, I want to use it for a security question of whether a database entry should be deleted. It's no problem to show the dialogue, but I can't find a way to integrate a function if the delete is confirmed.

That is the code for now:

    <script>
        Swal.fire({
            title: '',
            text: "Diesen Eintrag wirklich löschen?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Ja',
            cancelButtonText: 'Nein',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire(
                '<Here a function if delete is confirmed>'
                )
            } else {
                Swal.fire(
                '<Here a function to go back>'
                )
            }
        })
    </script>
    
    <?php
    public function deleteConfimred(){
        // Delete the entry
    }

Solution

  • You could submit a form using JS which submits to the PHP file where your function is.

    HTML:

    <form id="yourFormId" action="yourphpfile.php" method="post">
        <input type="hidden" name="delete" value="">
    </form>
    <button type="button" onclick="confirmDelete()">Delete</button>
    
    <script>
    function confirmDelete() {
        Swal.fire({
            title: '',
            text: "Diesen Eintrag wirklich löschen?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Ja',
            cancelButtonText: 'Nein',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                document.getElementById("yourFormId").submit();
            }
        })
    }
    </script>
    

    yourphpfile.php:

    <?php
    if(isset($_POST['delete'])) {
     deleteConfirmed();
    }
    
    public function deleteConfirmed(){
        // Delete the entry
    }
    ?>