I have created a simple html & bootstrap contact form which is backed by PHPMailer class to send an email. The program works perfectly till the sending of email. However, it is not showing the success/failure message on the same page and not clearing the fields also.
The code which I have written for my demo program is below. Please append your solutions to the same code rather making another code of your own.
index.html
<form method="post" action="mail.php" id="contact-form" role="form">
<div class="card-header">
<h2 class="font-weight-bold text-center my-4">Contact us</h2>
<p class="text-center mx-auto mb-5">Do you have any questions? Please do not hesitate to
contact us directly. Our team will come back to you within
a matter of hours to help you.</p>
<div class="alert alert-success" id="success-message"><span>Thank you for contacting us. We will
be in touch
soon.</span></div>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-6">
<div class="form-group ">
<label for="name" class="is-required">Name</label>
<input type="text" name="name" id="name" class="form-control" minlength="3"
required>
</div>
</div>
<div class="col-md-6">
<div class="form-group ">
<label for="email" class="is-required">email</label>
<input type="email" name="email" id="email" class="form-control" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="message" class="is-required">Message</label>
<textarea name="message" id="message" rows="2" class="form-control"
required></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="text-center text-md-left">
<input type="hidden" name="action" value="sendEmail" />
<button id="submit-button" name="submit" type="submit" value="Send"
class="btn btn-primary"><span>Send</span></button>
</div>
<div class="status" id="status"></div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="status" id="status"></div>
</div>
</div>
</div>
</form>
jQuery/ajax
<script>
$('form').validate();
$(document).ready(() => {
$('#success-message').hide();
$('form').submit((e) => {
let formData = {
'name': $('#name').val(),
'email': $('#email').val(),
'message': $('#message').val(),
'submit': 1
};
$.ajax({
type: 'POST',
url: 'mail.php',
data: formData,
dataType: 'json',
encode: true
}).done((data) => {
if (data.success) {
$('#success-message').show();
} else {
alert('Something went wrong. Please try again!');
}
});
e.preventDefault();
});
});
</script>
mail.php
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// Load Composer's autoloader
require 'vendor/autoload.php';
// header('Content-Type: application/json');
if (isset($_POST['submit'])) {
$name = $_POST['name']; // Sender's name
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$message = $_POST['message']; // Sender's message
$errorEmpty = false;
$errorEmail = false;
if (empty($name) || empty($email) || empty($message)) {
echo "<span class='alert alert-danger'> Name is required.</span>";
$errorEmpty = true;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='alert alert-danger'> Please try entering a correct email.</span>";
$errorEmail = true;
}
// Instantiate PHPMailer class
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'mymail@gmail.com'; // SMTP username
$mail->Password = 'mypass'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('mymail@gmail.com', 'My Name');
$mail->addAddress($email, $name); // Add a recipient
$body = '<p>Hello <strong> Mr. ' . $name . '</strong> <br /><br /> We have received your enquiry "' .$message. '". <br /> We ensure you that the team is working on it. <br /><br /> Thank you. </p>';
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'We received your query.';
$mail->Body = $body;
// $mail->AltBody = strip_tags($body);
$mail->send();
// echo 'Message has been sent';
} catch (Exception $e) {
echo $e->errorMessage();
echo "Mailer Error: " . $mail->ErrorInfo;
}
} else {
echo "There was an error!";
}
?>
Your any help is highly appreciated. Thanks in advance.
You're not really trying here. You're making an XHR, but not even attempting to return the results in a format that will work with that, and neither are you returning an error code that will trigger your error handler. First of all, you need to set the correct content type:
header('Content-type: application/json');
Then handle errors or valid responses apropriately, giving results in JSON format:
} catch (Exception $e) {
//Some other code may be better, but anything other than 2xx will do for jQuery
http_response_code(400);
echo json_encode(['status' => false, 'errormessage' => $e->errorMessage(), 'errorinfo' => $mail->Errorinfo]);
exit;
}
echo json_encode(['status' => true]);
exit;
Note that if your check for isset($_POST['submit'])
fails, you should not say anything (you're currently displaying an error) - it's what will happen when they first load the page.