如何隐藏联系表单只有在成功提交后使用jQuery,而不是当提交表单时
如果验证失败,我希望表单仍然显示并允许输入,但如果全部成功,那么我希望显示成功消息,形式消失。此代码隐藏了成功或验证错误是否发生的形式。如何隐藏联系表单只有在成功提交后使用jQuery,而不是当提交表单时
$(document).ready(function(){
$("#send").click(function(e){
e.preventDefault();
$("#send").prop("disabled", true);
$(".hideloader").show();
$("#send").html("Sending <img src='img/ajax-loader.gif'>");
var form_data = $("#contact-form").serialize();
$.ajax({
type: 'POST',
url: 'contact-submit.php',
data: form_data
}).done(function(response) {
$("#server-results").hide().html(response).fadeIn("slow");
$("#send").prop("disabled", false);
$("#send").html("Send Enquiry");
$("#contact-form").hide();
});
});
});
只是使用电子邮件领域为例我的PHP代码如下所示:
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$message = "";
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
$message .= "Invalid email address. <br/>";
}
if($message) {
echo "<div class='red-error'><b>There were errors in your form:</b> <br/>" . $message . "</div>";
} else {
echo "<div class='green-success'>Thank you. We will respond to your enquiry as soon as possible.</div>";
}
}
假设您要验证在后端的形式,并且返回一个包含一个名为validated
财产响应对象验证时的1
值(和0
当验证失败),你的Ajax应该是这样的:
$.ajax({
type: 'POST',
url: 'contact-submit.php',
data: form_data,
}).done(function(response) {
if (response.validated) {
// logic for when response has validated == 1
$("#contact-form").hide();
$("#send").prop("disabled", false);
$("#send").html("Send Enquiry");
}
// we display the response html in both cases (validated or not)
$("#server-results").hide().html(response.html).fadeIn("slow");
});
,在php
,你需要与此类似(调整你的逻辑):
$response = [];
if ($some_condition) {
$response['validated'] = 1;
$response['html'] = '<div class='green-success'>Some success message</div>';
} else {
$response['validated'] = 0;
$response['html'] = '<div class='red-error'>Some error message</div>';
}
echo json.encode($response);
我编辑了我的原始问题以显示php。如果服务器端有验证错误,那么它应该显示红色背景的错误,如果没有验证错误和表单提交,那么绿色背景的消息应该显示,然后我可以发送电子邮件,隐藏表格等。 – Jonathan
我编辑了我的答案区分服务器错误和自定义逻辑错误。服务器错误将调用'$ .ajax()'的'错误'函数。成功的调用,包括所有可能的定制逻辑结果,都会调用你的'success'函数,这就是你必须解析'response'的地方。 –
感谢您的回复。我仍然不明白这一点。对不起,我习惯于只使用php而不使用jQuery/AJAX。我如何得到这个: 'if(response.validated){validated,{012}}验证,隐藏你的表单' 显示绿色背景成功消息,else语句显示红色背景,服务器端验证错误按照PHP的? – Jonathan
如何测试在.done反应? – Jonathan