php - 提交按钮卡在处理 ajax 邮件表单/可能进行重定向
问题描述
我对ajax,php很陌生。我查看了其他建议,但仍然不确定是否找到了答案。我的问题是我有一个发送电子邮件的 ajax 表单。电子邮件功能提交正常(获得 200 响应代码)并被接收,但提交按钮卡在“发送...”文本上。该表单已连接到谷歌验证码,所以不确定这是否是它挂起的原因。
此外,我真正想做的是将页面重定向(刷新)到网站本身的不同页面。任何帮助,洞察力将不胜感激。同样,我对此很陌生,并试图通过我所知道的几件事来即时修复。
下面是我正在使用的代码:
HTML/JS:
<form id="contact_form" method="post" action="mailer.php">
<div class="hiddenFields">
<input type="hidden" name="XID" value="XXXXXXXXXX" />
<input type="hidden" name="ACT" value="17" />
<input type="hidden" name="RET" value="" />
<input type="hidden" name="URI" value="services" />
<input type="hidden" name="recipients" value="XXXXXXXXX"
/>
<input type="hidden" name="user_recipients" value="XXXXXXX" />
<input type="hidden" name="charset" value="utf-8" />
<input type="hidden" name="redirect" value="" />
<input type="hidden" name="replyto" value="" />
<input type="hidden" name="site_id" value="1" />
</div>
<div class="input_wrap">
<label for="name">Name</label>
<input type="text" id="name" name="name" class="required" />
</div>
<div class="input_wrap">
<label for="name">Company</label>
<input type="text" id="company" name="company" />
</div>
<div class="input_wrap">
<label for="from">Email</label>
<input type="text" id="from" name="from" class="required email" />
</div>
<div class="input_wrap">
<label for="message">Message</label>
<textarea id="message" name="message"></textarea>
</div>
<div class="g-recaptcha" data-sitekey="XXXXXXXXXXXXXX" data-
callback="onReCaptchaSuccess"></div>
<input id="submit" name="submit" type="submit" value="Submit" />
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-
FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="static/js/libs/jquery.validate.min.js"></script>
<script>
$(document).ready(function () {
$('input, textarea').focus(function () {
var $label = $('label[for="' + $(this).attr('id') + '"]');
$label.hide();
});
$('input, textarea').blur(function () {
var $label = $('label[for="' + $(this).attr('id') + '"]');
if (!$(this).val().length) $label.show();
});
$('html').on('click', function (e) {
var clicked = $(e.target);
if (clicked[0].id == 'submit') {
$('#contact_form').validate({
submitHandler: function (form) {
submitemail();
}
});
}
});
});
function submitemail() {
var _submit = $("#submit");
_submit.val("Sending . . .");
_submit.attr("disabled", "disabled");
var postData = $("#contact_form").serializeArray();
var formURL = $("#contact_form").attr("action");
$.ajax({
url: formURL,
type: "POST",
dataType:"json",
data: postData,
success: function (data, textStatus, jqXHR) {
//data: return data from server
console.log(data.status);
var status = data.status
if (status == "success") {
_submit.val("Submitted Successfully");
} else {
_submit.val("Error with server");
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("Our email server isn't responding");
}
});
}
</script>
<?php
// My modifications to mailer script from:
// http://blog.teamtreehouse.com/create-ajax-contact-form
// Added input sanitizing to prevent injection
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$company = $_POST["company"];
$email = filter_var(trim($_POST["from"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
}if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo 'Please check the the captcha form.';
exit;
}
$secretKey = "XXXXX";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify? secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo 'Please check Recaptcha';
} else {
echo '';
}
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "email@gmail.com";
// Set the email subject.
$subject = "Subject from $email";
// Build the email content.
$email_content = "Name: $name\n";
$email_content = "Company: $company\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $email <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
?>
解决方案
我认为在处理从 AJAX 调用获得的结果时出现错误:
您尝试进入变量status
内部。只是来自服务器的响应的主体,在您的情况下,您在 PHP 中的所有内容。data
data
echo
这应该是一个可行的解决方案:
success: function (data, textStatus, jqXHR) {
//data: return data from server
var status = jqXHR.status
if (status == 200) {
_submit.val("Submitted Successfully");
// Redirect:
window.location.href = "/success";
} else {
_submit.val("Error with server");
}
},
如您所见,我更改data.status
为jqXHR.status
. 这将返回 HTTP 状态代码,因此您必须检查200
(这是您在 PHP 中设置的内容以及用于成功请求的内容)。
另外,我补充window.location.href = "/success";
说,您可以在那里重定向到另一个页面。
推荐阅读
- python - python列表的子集基于相同列表的元素组,pythonically
- mongodb - 在 Java 驱动程序中为 MongoDB 使用聚合时出现光标错误
- c++ - declaration inside if condition
- spring-boot - 从 cmd 调用 java -jar app.jar --spring.config.location=file:///Users/home/config/jdbc.properties 时出现白标签错误
- django-models - 如何解决 NoReverseMatch?
- java - 使用 TransformerFactory 的 XSLT Transformer 增加元空间
- laravel - 在我安装了“hardevine/shoppingcart”包之后,出现“此集合实例上不存在属性 [id]”错误
- docker - 在运行时不带引号传递 env 变量
- php - 如何根据特定条件计算总和
- android - Firebase 注册问题