を使用して、各テキストフィールドの個々のエラーを表示するには、どのように、私は通常、このような何かを(私は通常(するpreg_matchを使用します)が、単に簡単のため)(空を使用して)しまうAJAXを使用せずに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