i have a simple php form, on form submit i want to display sweet alert, i did the following code:
JavaScript
x
29
29
1
<script src="https://unpkg.com/sweetalert2@7.8.2/dist/sweetalert2.all.js"></script>
2
3
<?php
4
if(isset($_POST['submit'])){
5
.
6
7
..
8
9
mail($to,$subject,$message,$headers);
10
11
echo "<script type='text/javascript'>";
12
echo "swal({
13
title: 'Your Message Was Sent Successfully',
14
type: 'success',
15
16
confirmButtonColor: '#DD6B55',
17
confirmButtonText: 'CLOSE',
18
}).then(() => {
19
if (result.value) {
20
// handle Confirm button click
21
} else {
22
// result.dismiss can be 'cancel', 'overlay', 'esc' or 'timer'
23
}
24
});";
25
echo "</script>";
26
27
28
}
29
?>
howerver sweetalert doesnt show up after formsubmit, can anyone please tell me what is wrong in here, thanks in advance
Advertisement
Answer
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:
JavaScript
1
29
29
1
<script src="https://unpkg.com/sweetalert2@7.8.2/dist/sweetalert2.all.js"></script>
2
3
<?php
4
if(isset($_POST['submit'])){
5
mail($to,$subject,$message,$headers);
6
// Simple span
7
echo '<span></span>';
8
9
10
echo "<script type='text/javascript'>";
11
echo "swal({
12
title: 'Your Message Was Sent Successfully',
13
type: 'success',
14
15
confirmButtonColor: '#DD6B55',
16
confirmButtonText: 'CLOSE',
17
}).then(() => {
18
if (result.value) {
19
// handle Confirm button click
20
} else {
21
// result.dismiss can be 'cancel', 'overlay', 'esc' or 'timer'
22
}
23
});";
24
echo "</script>";
25
26
27
}
28
?>
29
Or you can use AJAX if you use jQuery Instead of alert like this:
JavaScript
1
35
35
1
<script src="https://unpkg.com/sweetalert2@7.8.2/dist/sweetalert2.all.js"></script>
2
<script src="https://unpkg.com/jquery@3.6.0/dist/jquery.min.js"></script>
3
4
<?php
5
if(isset($_POST['submit'])){
6
mail($to,$subject,$message,$headers);
7
}
8
?>
9
10
<script>
11
$("YOUR FORM NAME OR ID").on('submit', (e) => {
12
// prevent default for not realoding after sent
13
e.preventDefault();
14
15
$.ajax({
16
url: "YOUR URL FOR SUBMIT FORM",
17
type: "POST"
18
}).done(() => {
19
// Our request submited
20
swal({
21
title: 'Your Message Was Sent Successfully',
22
type: 'success',
23
confirmButtonColor: '#DD6B55',
24
confirmButtonText: 'CLOSE',
25
}).then(() => {
26
if (result.value) {
27
// handle Confirm button click
28
} else {
29
// result.dismiss can be 'cancel', 'overlay', 'esc' or 'timer'
30
}
31
});
32
})
33
})
34
</script>
35