联系表格提交后显示错误消息:使用 PHP-mailer
Contact Form Displaying incorrect message after submission: using PHP-mailer
我是 PHP 的新手,真的很想得到一些帮助...此时我正在用头撞墙。我想要做的就是完成一个有效的联系表...使用 php-mailer。电子邮件正常通过,但问题在于单击提交后显示的消息。由于电子邮件已成功发送,消息应显示为“您的消息已发送给我们。”,如果未通过,则消息应显示为“错误,发送您的消息时出错。”提交后的消息无论如何都会显示错误信息。上网查了下也没用,希望大家帮帮忙。
我包括了 JS、PHP 和表单。
提前致谢。
<form class="contact-form" action="php/contact-form.php" method="POST">
<div class="contact-form-success alert alert-success d-none mt-4">
<strong>Success!</strong> Your message has been sent to us.
</div>
<div class="contact-form-error alert alert-danger d-none mt-4">
<strong>Error!</strong> There was an error sending your message.
<span class="mail-error-message text-1 d-block"></span>
</div>
<!-- ...... -->
</form>
<?php
namespace PortoContactForm;
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));
header('Content-type: application/json');
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'php-mailer/src/PHPMailer.php';
require 'php-mailer/src/SMTP.php';
require 'php-mailer/src/Exception.php';
// Step 1 - Enter your email address below.
$email = 'alex@alexleloup.com';
// If the e-mail is not working, change the debug option to 2 | $debug = 2;
$debug = 1;
// If contact form don't has the subject input change the value of subject here
$subject = ( isset($_POST['subject']) ) ? $_POST['subject'] : 'Define subject in php/contact-form.php line 29';
$message = '';
foreach($_POST as $label => $value) {
$label = ucwords($label);
// Use the commented code below to change label texts. On this example will change "Email" to "Email Address"
// if( $label == 'Email' ) {
// $label = 'Email Address';
// }
// Checkboxes
if( is_array($value) ) {
// Store new value
$value = implode(', ', $value);
}
$message .= $label.": " . htmlspecialchars($value, ENT_QUOTES) . "<br>\n";
}
$mail = new PHPMailer(true);
try {
$mail->SMTPDebug = $debug; // Debug Mode
// Step 2 (Optional) - If you don't receive the email, try to configure the parameters below:
//$mail->IsSMTP(); // Set mailer to use SMTP
//$mail->Host = 'mail.alexleloup.com'; // Specify main and backup server
//$mail->SMTPAuth = true; // Enable SMTP authentication
//$mail->Username = ''; // SMTP username
//$mail->Password = ''; // SMTP password
//$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
//$mail->Port = 587; // TCP port to connect to
$mail->AddAddress($email); // Add another recipient
//$mail->AddAddress('person2@domain.com', 'Person 2'); // Add a secondary recipient
//$mail->AddCC('person3@domain.com', 'Person 3'); // Add a "Cc" address.
//$mail->AddBCC('person4@domain.com', 'Person 4'); // Add a "Bcc" address.
// From - Name
$fromName = ( isset($_POST['name']) ) ? $_POST['name'] : 'Website User';
$mail->SetFrom($email, $fromName);
// Reply To
if( isset($_POST['email']) ) {
$mail->AddReplyTo($_POST['email'], $fromName);
}
$mail->IsHTML(true); // Set email format to HTML
$mail->CharSet = 'UTF-8';
$mail->Subject = $subject;
$mail->Body = $message;
$mail->Send();
$arrResult = array ('response'=>'success');
} catch (Exception $e) {
$arrResult = array ('response'=>'error','errorMessage'=>$e->errorMessage());
} catch (\Exception $e) {
$arrResult = array ('response'=>'error','errorMessage'=>$e->getMessage());
}
if ($debug == 0) {
echo json_encode($arrResult);
}
Name: View - Contact
Written by: Okler Themes - (http://www.okler.net)
Theme Version: 8.0.0
*/
(function($) {
'use strict';
/*
Custom Rules
*/
// No White Space
$.validator.addMethod("noSpace", function(value, element) {
if( $(element).attr('required') ) {
return value.search(/[a-zA-Z0-9À-žа-яА-ЯёЁα-ωΑ-Ω\s\u0621-\u064A\u0660-\u0669 ]/i) == 0;
}
return true;
}, 'Please fill this empty field.');
/*
Assign Custom Rules on Fields
*/
$.validator.addClassRules({
'form-control': {
noSpace: true
}
});
/*
Contact Form: Basic
*/
$('.contact-form').each(function(){
$(this).validate({
submitHandler: function(form) {
var $form = $(form),
$messageSuccess = $form.find('.contact-form-success'),
$messageError = $form.find('.contact-form-error'),
$submitButton = $(this.submitButton),
$errorMessage = $form.find('.mail-error-message'),
submitButtonText = $submitButton.val();
$submitButton.val( $submitButton.data('loading-text') ? $submitButton.data('loading-text') : 'Loading...' ).attr('disabled', true);
// Fields Data
var formData = $form.serializeArray(),
data = {};
$(formData).each(function(index, obj){
data[obj.name] = obj.value;
});
// Google Recaptcha v2
if( data["g-recaptcha-response"] != undefined ) {
data["g-recaptcha-response"] = $form.find('#g-recaptcha-response').val();
}
// Ajax Submit
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: data
}).always(function(data, textStatus, jqXHR) {
$errorMessage.empty().hide();
if (data.response == 'success') {
// Uncomment the code below to redirect for a thank you page
// self.location = 'thank-you.html';
$messageSuccess.removeClass('d-none');
$messageError.addClass('d-none');
// Reset Form
$form.find('.form-control')
.val('')
.blur()
.parent()
.removeClass('has-success')
.removeClass('has-danger')
.find('label.error')
.remove();
if (($messageSuccess.offset().top - 80) < $(window).scrollTop()) {
$('html, body').animate({
scrollTop: $messageSuccess.offset().top - 80
}, 300);
}
$form.find('.form-control').removeClass('error');
$submitButton.val( submitButtonText ).attr('disabled', false);
return;
} else if (data.response == 'error' && typeof data.errorMessage !== 'undefined') {
$errorMessage.html(data.errorMessage).show();
} else {
$errorMessage.html(data.responseText).show();
}
$messageError.removeClass('d-none');
$messageSuccess.addClass('d-none');
if (($messageError.offset().top - 80) < $(window).scrollTop()) {
$('html, body').animate({
scrollTop: $messageError.offset().top - 80
}, 300);
}
$form.find('.has-success')
.removeClass('has-success');
$submitButton.val( submitButtonText ).attr('disabled', false);
});
}
});
});
/*
Contact Form: Advanced
*/
$('#contactFormAdvanced').validate({
onkeyup: false,
onclick: false,
onfocusout: false,
rules: {
'captcha': {
captcha: true
},
'checkboxes[]': {
required: true
},
'radios': {
required: true
}
},
errorPlacement: function(error, element) {
if (element.attr('type') == 'radio' || element.attr('type') == 'checkbox') {
error.appendTo(element.closest('.form-group'));
} else {
error.insertAfter(element);
}
}
});
/*
Contact Form: reCaptcha v3
*/
$('.contact-form-recaptcha-v3').each(function(){
$(this).validate({
submitHandler: function(form) {
var $form = $(form),
$messageSuccess = $form.find('.contact-form-success'),
$messageError = $form.find('.contact-form-error'),
$submitButton = $(this.submitButton),
$errorMessage = $form.find('.mail-error-message'),
submitButtonText = $submitButton.val();
$submitButton.val( $submitButton.data('loading-text') ? $submitButton.data('loading-text') : 'Loading...' ).attr('disabled', true);
var site_key = $('#google-recaptcha-v3').attr('src').split("render=")[1];
grecaptcha.execute(site_key, {action: 'contact_us'}).then(function(token) {
// Fields Data
var formData = $form.serializeArray(),
data = {};
$(formData).each(function(index, obj){
data[obj.name] = obj.value;
});
// Recaptcha v3 Token
data["g-recaptcha-response"] = token;
// Ajax Submit
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: data
}).always(function(data, textStatus, jqXHR) {
$errorMessage.empty().hide();
if (data.response == 'success') {
// Uncomment the code below to redirect for a thank you page
// self.location = 'thank-you.html';
$messageSuccess.removeClass('d-none');
$messageError.addClass('d-none');
// Reset Form
$form.find('.form-control')
.val('')
.blur()
.parent()
.removeClass('has-success')
.removeClass('has-danger')
.find('label.error')
.remove();
if (($messageSuccess.offset().top - 80) < $(window).scrollTop()) {
$('html, body').animate({
scrollTop: $messageSuccess.offset().top - 80
}, 300);
}
$form.find('.form-control').removeClass('error');
$submitButton.val( submitButtonText ).attr('disabled', false);
return;
} else if (data.response == 'error' && typeof data.errorMessage !== 'undefined') {
$errorMessage.html(data.errorMessage).show();
} else {
$errorMessage.html(data.responseText).show();
}
$messageError.removeClass('d-none');
$messageSuccess.addClass('d-none');
if (($messageError.offset().top - 80) < $(window).scrollTop()) {
$('html, body').animate({
scrollTop: $messageError.offset().top - 80
}, 300);
}
$form.find('.has-success')
.removeClass('has-success');
$submitButton.val( submitButtonText ).attr('disabled', false);
});
});
}
});
});
}).apply(this, [jQuery]);
问题似乎出在您正在设置的 PHP 脚本的顶部附近:
$debug = 1;
最后你说:
if ($debug == 0) {
echo json_encode($arrResult);
}
这会导致脚本不发送任何响应,或者至少不会是您期望的 {"'response": "success"}
json,这会导致此 js 检查失败:
if (data.response == 'success')
您需要设置 $debug = 0;
、删除 if ($debug == 0)
检查,或者以其他方式解决此逻辑问题。
我是 PHP 的新手,真的很想得到一些帮助...此时我正在用头撞墙。我想要做的就是完成一个有效的联系表...使用 php-mailer。电子邮件正常通过,但问题在于单击提交后显示的消息。由于电子邮件已成功发送,消息应显示为“您的消息已发送给我们。”,如果未通过,则消息应显示为“错误,发送您的消息时出错。”提交后的消息无论如何都会显示错误信息。上网查了下也没用,希望大家帮帮忙。 我包括了 JS、PHP 和表单。 提前致谢。
<form class="contact-form" action="php/contact-form.php" method="POST">
<div class="contact-form-success alert alert-success d-none mt-4">
<strong>Success!</strong> Your message has been sent to us.
</div>
<div class="contact-form-error alert alert-danger d-none mt-4">
<strong>Error!</strong> There was an error sending your message.
<span class="mail-error-message text-1 d-block"></span>
</div>
<!-- ...... -->
</form>
<?php
namespace PortoContactForm;
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));
header('Content-type: application/json');
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'php-mailer/src/PHPMailer.php';
require 'php-mailer/src/SMTP.php';
require 'php-mailer/src/Exception.php';
// Step 1 - Enter your email address below.
$email = 'alex@alexleloup.com';
// If the e-mail is not working, change the debug option to 2 | $debug = 2;
$debug = 1;
// If contact form don't has the subject input change the value of subject here
$subject = ( isset($_POST['subject']) ) ? $_POST['subject'] : 'Define subject in php/contact-form.php line 29';
$message = '';
foreach($_POST as $label => $value) {
$label = ucwords($label);
// Use the commented code below to change label texts. On this example will change "Email" to "Email Address"
// if( $label == 'Email' ) {
// $label = 'Email Address';
// }
// Checkboxes
if( is_array($value) ) {
// Store new value
$value = implode(', ', $value);
}
$message .= $label.": " . htmlspecialchars($value, ENT_QUOTES) . "<br>\n";
}
$mail = new PHPMailer(true);
try {
$mail->SMTPDebug = $debug; // Debug Mode
// Step 2 (Optional) - If you don't receive the email, try to configure the parameters below:
//$mail->IsSMTP(); // Set mailer to use SMTP
//$mail->Host = 'mail.alexleloup.com'; // Specify main and backup server
//$mail->SMTPAuth = true; // Enable SMTP authentication
//$mail->Username = ''; // SMTP username
//$mail->Password = ''; // SMTP password
//$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
//$mail->Port = 587; // TCP port to connect to
$mail->AddAddress($email); // Add another recipient
//$mail->AddAddress('person2@domain.com', 'Person 2'); // Add a secondary recipient
//$mail->AddCC('person3@domain.com', 'Person 3'); // Add a "Cc" address.
//$mail->AddBCC('person4@domain.com', 'Person 4'); // Add a "Bcc" address.
// From - Name
$fromName = ( isset($_POST['name']) ) ? $_POST['name'] : 'Website User';
$mail->SetFrom($email, $fromName);
// Reply To
if( isset($_POST['email']) ) {
$mail->AddReplyTo($_POST['email'], $fromName);
}
$mail->IsHTML(true); // Set email format to HTML
$mail->CharSet = 'UTF-8';
$mail->Subject = $subject;
$mail->Body = $message;
$mail->Send();
$arrResult = array ('response'=>'success');
} catch (Exception $e) {
$arrResult = array ('response'=>'error','errorMessage'=>$e->errorMessage());
} catch (\Exception $e) {
$arrResult = array ('response'=>'error','errorMessage'=>$e->getMessage());
}
if ($debug == 0) {
echo json_encode($arrResult);
}
Name: View - Contact
Written by: Okler Themes - (http://www.okler.net)
Theme Version: 8.0.0
*/
(function($) {
'use strict';
/*
Custom Rules
*/
// No White Space
$.validator.addMethod("noSpace", function(value, element) {
if( $(element).attr('required') ) {
return value.search(/[a-zA-Z0-9À-žа-яА-ЯёЁα-ωΑ-Ω\s\u0621-\u064A\u0660-\u0669 ]/i) == 0;
}
return true;
}, 'Please fill this empty field.');
/*
Assign Custom Rules on Fields
*/
$.validator.addClassRules({
'form-control': {
noSpace: true
}
});
/*
Contact Form: Basic
*/
$('.contact-form').each(function(){
$(this).validate({
submitHandler: function(form) {
var $form = $(form),
$messageSuccess = $form.find('.contact-form-success'),
$messageError = $form.find('.contact-form-error'),
$submitButton = $(this.submitButton),
$errorMessage = $form.find('.mail-error-message'),
submitButtonText = $submitButton.val();
$submitButton.val( $submitButton.data('loading-text') ? $submitButton.data('loading-text') : 'Loading...' ).attr('disabled', true);
// Fields Data
var formData = $form.serializeArray(),
data = {};
$(formData).each(function(index, obj){
data[obj.name] = obj.value;
});
// Google Recaptcha v2
if( data["g-recaptcha-response"] != undefined ) {
data["g-recaptcha-response"] = $form.find('#g-recaptcha-response').val();
}
// Ajax Submit
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: data
}).always(function(data, textStatus, jqXHR) {
$errorMessage.empty().hide();
if (data.response == 'success') {
// Uncomment the code below to redirect for a thank you page
// self.location = 'thank-you.html';
$messageSuccess.removeClass('d-none');
$messageError.addClass('d-none');
// Reset Form
$form.find('.form-control')
.val('')
.blur()
.parent()
.removeClass('has-success')
.removeClass('has-danger')
.find('label.error')
.remove();
if (($messageSuccess.offset().top - 80) < $(window).scrollTop()) {
$('html, body').animate({
scrollTop: $messageSuccess.offset().top - 80
}, 300);
}
$form.find('.form-control').removeClass('error');
$submitButton.val( submitButtonText ).attr('disabled', false);
return;
} else if (data.response == 'error' && typeof data.errorMessage !== 'undefined') {
$errorMessage.html(data.errorMessage).show();
} else {
$errorMessage.html(data.responseText).show();
}
$messageError.removeClass('d-none');
$messageSuccess.addClass('d-none');
if (($messageError.offset().top - 80) < $(window).scrollTop()) {
$('html, body').animate({
scrollTop: $messageError.offset().top - 80
}, 300);
}
$form.find('.has-success')
.removeClass('has-success');
$submitButton.val( submitButtonText ).attr('disabled', false);
});
}
});
});
/*
Contact Form: Advanced
*/
$('#contactFormAdvanced').validate({
onkeyup: false,
onclick: false,
onfocusout: false,
rules: {
'captcha': {
captcha: true
},
'checkboxes[]': {
required: true
},
'radios': {
required: true
}
},
errorPlacement: function(error, element) {
if (element.attr('type') == 'radio' || element.attr('type') == 'checkbox') {
error.appendTo(element.closest('.form-group'));
} else {
error.insertAfter(element);
}
}
});
/*
Contact Form: reCaptcha v3
*/
$('.contact-form-recaptcha-v3').each(function(){
$(this).validate({
submitHandler: function(form) {
var $form = $(form),
$messageSuccess = $form.find('.contact-form-success'),
$messageError = $form.find('.contact-form-error'),
$submitButton = $(this.submitButton),
$errorMessage = $form.find('.mail-error-message'),
submitButtonText = $submitButton.val();
$submitButton.val( $submitButton.data('loading-text') ? $submitButton.data('loading-text') : 'Loading...' ).attr('disabled', true);
var site_key = $('#google-recaptcha-v3').attr('src').split("render=")[1];
grecaptcha.execute(site_key, {action: 'contact_us'}).then(function(token) {
// Fields Data
var formData = $form.serializeArray(),
data = {};
$(formData).each(function(index, obj){
data[obj.name] = obj.value;
});
// Recaptcha v3 Token
data["g-recaptcha-response"] = token;
// Ajax Submit
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: data
}).always(function(data, textStatus, jqXHR) {
$errorMessage.empty().hide();
if (data.response == 'success') {
// Uncomment the code below to redirect for a thank you page
// self.location = 'thank-you.html';
$messageSuccess.removeClass('d-none');
$messageError.addClass('d-none');
// Reset Form
$form.find('.form-control')
.val('')
.blur()
.parent()
.removeClass('has-success')
.removeClass('has-danger')
.find('label.error')
.remove();
if (($messageSuccess.offset().top - 80) < $(window).scrollTop()) {
$('html, body').animate({
scrollTop: $messageSuccess.offset().top - 80
}, 300);
}
$form.find('.form-control').removeClass('error');
$submitButton.val( submitButtonText ).attr('disabled', false);
return;
} else if (data.response == 'error' && typeof data.errorMessage !== 'undefined') {
$errorMessage.html(data.errorMessage).show();
} else {
$errorMessage.html(data.responseText).show();
}
$messageError.removeClass('d-none');
$messageSuccess.addClass('d-none');
if (($messageError.offset().top - 80) < $(window).scrollTop()) {
$('html, body').animate({
scrollTop: $messageError.offset().top - 80
}, 300);
}
$form.find('.has-success')
.removeClass('has-success');
$submitButton.val( submitButtonText ).attr('disabled', false);
});
});
}
});
});
}).apply(this, [jQuery]);
问题似乎出在您正在设置的 PHP 脚本的顶部附近:
$debug = 1;
最后你说:
if ($debug == 0) {
echo json_encode($arrResult);
}
这会导致脚本不发送任何响应,或者至少不会是您期望的 {"'response": "success"}
json,这会导致此 js 检查失败:
if (data.response == 'success')
您需要设置 $debug = 0;
、删除 if ($debug == 0)
检查,或者以其他方式解决此逻辑问题。