I'm trying to output a SweetAlert2 message box when a user leaves a username/password input box empty.
if(empty($_POST["username"]) || empty($_POST["password"]))
{
echo '<script language="javascript">';
echo 'Swal.fire({
type: \"error\",
title: \"Oops...\",
text: \"Please provide login credentials!\"
})';
echo '</script>';
}
I've included \\ to escape quotes but no message box is appearing at all. Any ideas?
To avoid a lot of escaping I normally write larger HTML blocks inside of PHP like this:
<?php
if(empty($_POST["username"]) || empty($_POST["password"])) {
?>
<script>
Swal.fire({
type: "error",
title: "Oops...",
text: "Please provide login credentials!"
});
</script>
<?php } ?>
Your code is not producing valid JavaScript because the escape \\
is not necessary and therefor will be outputted. The JavaScript engine of your browser does not know what type: \\"error\\"
should be and probably you will see an error in your console.
Make sure to include SweetAlert2 BEFORE your code for showing the alert (example for using the CDN):
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
Maybe you have this include at the bottom of your body but your condition is in the middle of your page?
EDIT: The language
attribute for the HTML <script/>
element is deprecated and should be ommited.
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.