Я создал простую контактную форму html & bootstrap, которая поддерживается классом PHPMailer для отправки электронного письма. Программа отлично работает до отправки электронной почты. Тем не менее, он не показывает сообщение об успехе / неудаче на той же странице и не очищает поля также.
Код, который я написал для моей демонстрационной программы, приведен ниже. Пожалуйста, добавьте ваши решения к тому же коду, а не создавайте свой собственный.
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!";
}
?>
Ваша любая помощь высоко ценится. Заранее спасибо.