不使用AJAX来显示每个文本字段个人失误,我通常会做这样的事情(我通常会使用的preg_match(),但只用空的()为简单起见)如何用ajax PHP
$message = "";
if (empty($_POST['first_name'])) {
$message. = "First name required
";
}
if (empty($_POST['last_name'])) {
$message. = "Last name required";
if ($message) {
echo "
"
} else {
// write to db, send email etc.
}
}
我想用这个AJAX。我自己做了一点,并得到了一些帮助,但我现在的问题是,我只能得到错误消息来显示,但我想要做我在上面的例子中所做的。
$(function() {
$("#send").click(function(e){
e.preventDefault();
$("#send").prop("disabled", true);
$(".loader").show();
$("#send").html("Sending ");
var form_data = $("#contact-form").serialize();
$.ajax({
type: 'POST',
url: 't2329.php',
data: form_data,
dataType: 'JSON'
}).done(function(response) {
$(".loader").hide();
$("#server-results").hide().html(response.message).fadeIn("slow");
$('#send').html('Send Enquiry').prop({disabled: false});
if (response.status) {
$('#contact-form').hide();
}
});
});
});
if ($_POST) {
$response = new stdClass;
$response->message = "";
$response->status = false;
$email = isset($_POST['email']) ? $_POST['email'] : '';
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$response->status = true;
}
if($response->status === false) {
$response->message = <<< MSG
There were errors in your form:
Invalid email address.
MSG;
}
else {
// WRITE TO DB HERE
// SEND EMAIL HERE
$response->message = <<< MSG
MSG;
}
die(json_encode($response));
}
2017-04-19
Jonathan
+0
更好的使用jQuery验证器: - https://www.sitepoint.com/basic-jquery-form-validation-tutorial/。很容易使用和大量的代码将减少。 –
+0
虽然我想使用服务器端验证,但不是jQuery验证。 –