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
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:
Alternatively, if you use jQuery instead of an alert like this, you can use AJAX :