Home > Net >  sweetalert not working in php after form submission
sweetalert not working in php after form submission

Time:06-22

i have a simple php form, on form submit i want to display sweet alert, i did the following code:

<script src="https://unpkg.com/[email protected]/dist/sweetalert2.all.js"></script>

<?php
if(isset($_POST['submit'])){
....
...
.....

    mail($to,$subject,$message,$headers);
  
 echo "<script type='text/javascript'>";
 echo "swal({
    title: 'Your Message Was Sent Successfully',
    type: 'success',

    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'CLOSE',
  }).then(() => {
    if (result.value) {
      // handle Confirm button click
    } else {
      // result.dismiss can be 'cancel', 'overlay', 'esc' or 'timer'
    }
  });";
 echo "</script>";


        }
?>

howerver sweetalert doesnt show up after formsubmit, can anyone please tell me what is wrong in here, thanks in advance

CodePudding user response:

Because your body is empty and sweetalert append your code to empty body & you got error in your console like this:

console error

If you want to send alert with this method, you should have something in your body.

For example I echo simple span on my code and it's work for me:

<script src="https://unpkg.com/[email protected]/dist/sweetalert2.all.js"></script>

<?php
if(isset($_POST['submit'])){
    mail($to,$subject,$message,$headers);
    // Simple span
    echo '<span></span>';

  
 echo "<script type='text/javascript'>";
 echo "swal({
    title: 'Your Message Was Sent Successfully',
    type: 'success',

    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'CLOSE',
  }).then(() => {
    if (result.value) {
      // handle Confirm button click
    } else {
      // result.dismiss can be 'cancel', 'overlay', 'esc' or 'timer'
    }
  });";
 echo "</script>";


        }
?>

Or you can use AJAX if you use jQuery Instead of alert like this:

<script src="https://unpkg.com/[email protected]/dist/sweetalert2.all.js"></script>
<script src="https://unpkg.com/[email protected]/dist/jquery.min.js"></script>

<?php
if(isset($_POST['submit'])){
    mail($to,$subject,$message,$headers);
}
?>

<script>
    $("YOUR FORM NAME OR ID").on('submit', (e) => {
        // prevent default for not realoding after sent
        e.preventDefault();

        $.ajax({
            url: "YOUR URL FOR SUBMIT FORM",
            type: "POST"
        }).done(() => {
            // Our request submited
            swal({
            title: 'Your Message Was Sent Successfully',
            type: 'success',
            confirmButtonColor: '#DD6B55',
            confirmButtonText: 'CLOSE',
            }).then(() => {
            if (result.value) {
                // handle Confirm button click
            } else {
                // result.dismiss can be 'cancel', 'overlay', 'esc' or 'timer'
            }
            });
        })
    })
</script>
  • Related