How to use sweet alert in PHP
Posted on: February 11, 2021 by Deven
In this short article, I will share how to use sweet alert in PHP. consider the following example.
Step 1. Create a file Form.html
with the following code:
<form role="form" id="contact-form" method="post">
<label for="name">Name</label>
<input type="text" placeholder="Full Name" name="name" required>
<label for="email">Email</label>
<input type="email" placeholder="Your Email" name="email" required>
<label>Message</label>
<textarea name="message" placeholder="Your Message" rows="9"></textarea>
<button type="submit" class="btn">Send</button>
</form>
step 2. Create a file called main.js
with the following code:
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#contact-form').on('submit',function(e) { //Don't foget to change the id form
$.ajax({
url:'contact.php', //===PHP file name====
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
//Success Message == 'Title', 'Message body', Last one leave as it is
swal("¡Success!", "Message sent!", "success");
},
error:function(data){
//Error Message == 'Title', 'Message body', Last one leave as it is
swal("Oops...", "Something went wrong :(", "error");
}
});
e.preventDefault(); //This is to Avoid Page Refresh and Fire the Event "Click"
});
});
</script>
step 3 – create file contact.php
with the following code:
<?php
$to = 'your@email.com' . "\r\n";
$subject = 'Subject';
$name = $_POST['nombre'];
$email = $_POST['email'];
$message = "************************************************** \r\n" .
"Message from you website! \r\n" .
"************************************************** \r\n" .
"Name: " . $name . "\r\n" .
"E-mail: " . $email . "\r\n" .
"Message: " . $_POST["message"] . "\r\n";
$headers = "From: " . $name . "<" . $email . "> \r\n" .
"Reply-To: " . $email . "\r\n" .
"MIME-Version: 1.0" . "\r\n" .
"Content-type:text/html;charset=UTF-8" . "\r\n";
mail($to, $subject, $message, $headers);
?>
Finally, Test and run it on your browser, make sure you have Xampp or Wamp installed in your computer before you run this locally.
Share on social media
//