<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX form check</title>
</head>
<body>
<form action="validator.php" method="POST" id="myForm">
<label>Name: </label>
<input type="text" class="form-group" name="name" />
<span class="error-name error">Missing Name</span>
<br>
<label>Email: </label>
<input type="email" class="form-group" name="email" />
<span class="error-email error">Missing Email</span>
<br>
<button type="submit">Submit</button>
</form>
<div id="message"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
.error {display:none;color:red;}
$(document).ready(function(){
$('#myForm').submit(function(e){
// Remove the default function of form element
e.preventDefault();
// Hide the error if success
$('.error').hide();
// Serializing data
var data = $(this).serialize();
// Message after send
$('#message').html('Sending...');
console.log(data);
$.ajax({
type: 'POST',
url: 'validator.php',
data: data,
dataType: 'json',
success: function(d) {
console.log(d);
// Message 'FAIL'
$('#message').html('<div>'+ d.message +'</div>');
// Condition if it's success
if (d.success) {
// Message 'SUCCESS'
$('#message').html('<div>'+ d.message +'</div>');
} else {
// Condition if errors name or email isn't exists, show the error and text.
if (d.errors.name) $('span.error-name').show().text(d.errors.name);
if (d.errors.email) $('span.error-email').show().text(d.errors.email);
}
}
});
});
});