I want the form to still show and allow input if a failed validation occurs but if all succeeds then I want the success message to show and the form to disappear. This code hides the form whether success or validation errors occur.
$(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();
});
});
});
My php code just using an email field as an example looks like this:
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>";
}
}