我希望表单仍然显示并允许输入如果验证失败但是如果所有成功,那么我希望显示成功消息并且表单消失。此代码隐藏表单是否发生成功或验证错误。
$(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>";
}
}
答案 0 :(得分:0)
假设您在后端验证表单,并在验证时返回包含名为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);