Home  >  Q&A  >  body text

sweetalert not working in php after form submission

I have a simple PHP form and when the form is submitted I want to show a sweet alert, I made 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>";


        }
?>

However, sweetalert does not appear after the form is submitted. Can anyone tell me what is wrong here? Thank you in advance

P粉354602955P粉354602955288 days ago395

reply all(1)I'll reply

  • P粉504080992

    P粉5040809922024-01-29 17:22:57

    Because your body is empty and sweetalert appends your code to the empty body and you get an error in your console like this:

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

    For example, I echoed a simple span on code and it worked for me:

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

    Alternatively, if you use jQuery instead of an alert like this, you can use AJAX :

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

    reply
    0
  • Cancelreply