我制作了一个AJAX
用于发送消息的联系表格(自定义)。现在我不清楚如何验证表单。
AJAX 请求:
$("#contact-form").on("submit", function (e) {
e.preventDefault();
var action = "contact_form";
$("#submit, #clear").prop("disabled", true);
$("#submit").html("Sending");
$.ajax({
url: $(this).attr("action"),
method: "post",
data: {
name: $("#name").val(),
email: $("#email").val(),
phone: $("#phone").val(),
subject: $("#subject").val(),
message: $("#message").val(),
action: action,
},
success: function () {
$("header").append(
"<div id='alert' class='alert alert-success alert-dismissible fixed-top' role='alert' >" +
"<p class='text-center'>Success</p>" +
"<button type = 'button' class='close' data-dismiss = 'alert'>×</button>" +
"</div>"
);
$("#submit, #clear").prop("disabled", false);
// $("#contact-form input,textarea").val("");
grecaptcha.reset();
$("#submit").html("Send");
},
error: function () {
$("header").append(
"<div id='alert' class='alert alert-danger alert-dismissible fixed-top' role='alert' >" +
"<p class='text-center'>Error</p>" +
"<button type = 'button' class='close' data-dismiss = 'alert'>×</button>" +
"</div>"
);
$("#submit, #clear").prop("disabled", false);
grecaptcha.reset();
$("#submit").html("Send");
},
});
});
});
函数.php:
function contact_form() // this is the action data variable we set in ajax
{
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// preparing parameters for wp_mail();
$to = "[email protected]";
$msg = "
Name: $name
Email: $email
Phone: $phone
$message
";
// sending mail using wp_mail function
wp_mail($to, $subject, $msg);
wp_die(); // must use wp_die() to avoid unwanted output from wordpress
}
// in first parameter prefix function name with wp_ajax_
// this action is required in order to recieve data sent from ajax
add_action( 'wp_ajax_contact_form', 'contact_form' );
add_action( 'wp_ajax_nopriv_contact_form', 'contact_form' );
现在,当我不尝试使用时,我通常会在ajax
php 文件中执行预制验证,例如,如果验证码无效,我会将状态附加到GET
方法并返回错误。如果有人可以指出我如何在 php 文件中验证并将信息返回到前端的正确方向,还是应该在 js 文件中进行验证?我很困惑,网上有这么多文章,老实说,我不知道在哪里看。
PS 一切正常,只是为了验证它。
验证两种方式。JS 验证可实现流畅的 UX,并处理有关有效电子邮件地址、非空字段等的大多数问题。
PHP 验证将确保您的函数不会出错,并允许您进行一些服务器端检查(例如之前未发送过确切消息等)
在 php 中,进行验证检查并准备任何错误的 json 响应,然后在出现错误时回显(而不是继续执行代码)。在 JS 中捕获成功块中的错误 - 现在它不会监听任何响应。
PHP:
if ($errors) {
echo json_encode(array('status' => 'error', 'message' => 'Your email message has objectionable content'));
wp_die();
}
if (!wp_mail($to, $subject, $msg)) {
echo json_encode(array('status' => 'error', 'message' => 'Your email message did not send for some reason'));
wp_die();
}
echo json_encode(array('status' => 'success');
wp_die();
你的JS
// ajax...
$.ajax({
... your props
dataType: 'json',
success: function (response) {
if (response && response.status == 'error'){
$('errors').html("Sorry, your message did not get sent due to these errors: " + response.message);
return;
} else {
// .. success
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句