简体   繁体   中英

sweetalert not working in php after form submission

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/sweetalert2@7.8.2/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

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

控制台错误

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/sweetalert2@7.8.2/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/sweetalert2@7.8.2/dist/sweetalert2.all.js"></script>
<script src="https://unpkg.com/jquery@3.6.0/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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM