不使用AJAX來顯示每個文本字段個人失誤,我通常會做這樣的事情(我通常會使用的preg_match(),但只用空的()爲簡單起見)如何用ajax PHP
$message = "";
if (empty($_POST['first_name'])) {
$message. = "First name required <br/>";
}
if (empty($_POST['last_name'])) {
$message. = "Last name required";
if ($message) {
echo "<div class='alert alert-danger'>".$message.
"</div>";
} else {
// write to db, send email etc.
}
}
我想用這個AJAX。我自己做了一點,並得到了一些幫助,但我現在的問題是,我只能得到錯誤消息來顯示,但我想要做我在上面的例子中所做的。
<script>
$(function() {
$("#send").click(function(e){
e.preventDefault();
$("#send").prop("disabled", true);
$(".loader").show();
$("#send").html("Sending <img src='img/ajax-loader.gif'>");
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();
}
});
});
});
</script>
<?php
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
<div class="red-error">
<b>There were errors in your form:</b><br/>
Invalid email address. <br/>
</div>
MSG;
}
else {
// WRITE TO DB HERE
// SEND EMAIL HERE
$response->message = <<< MSG
<div class="green-success">Thank you. We will respond to your enquiry as soon as possible.</div>
MSG;
}
die(json_encode($response));
}
任何控制檯錯誤? – madalinivascu
更好的使用jQuery驗證器: - https://www.sitepoint.com/basic-jquery-form-validation-tutorial/。很容易使用和大量的代碼將減少。 –
雖然我想使用服務器端驗證,但不是jQuery驗證。 – Jonathan