I have a validation check with ajax and it will show errors. However, it will show the error and then immediately go to the form send page displaying the errors.
The page is incredibly long - so I'll paste an example of what I have for the ajax section.
I should note that everything here programmatically works as intended - the only problem is that it will display the error via ajax (as it should) then redirects to submit_form.php after a couple of seconds with the error message displayed in plain text.
HTML
<form action="submit_form.php" method="post" id="form_1">
<input type="text" name="text_box" class="form-control" id="text_box" placeholder="Enter Text Here">
<button type="submit" name="submit_form" id="submit_form" class="btn btn-primary">Submit</button>
</form>
JS
<script>
$('#submit_form).on('click', function () {
$.ajax({
type: "POST",
url: "submit_form.php",
dataType: "json",
data: $('#form_1').serialize(),
success: function (json) {
$('.message_center').html('');
if(json['success']) {
$('.message_center').html('<div class="row">'+
' <div class="col-md-12">'+
' <div class="alert alert-success alert-dismissible">'+
' <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+
' <h4><i class="icon fa fa-check"></i> Success!</h4>'+
' '+json['success']+''+
' </div>'+
' </div>'+
' </div> ');
}
if(json['error']) {
var html='';
$.each( json['error'], function( key, value ) {
html += value+'<br>';
});
$('.message_center').html('<div class="row">'+
' <div class="col-md-12">'+
' <div class="alert alert-warning alert-dismissible">'+
' <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'+
' <h4><i class="icon fa fa-warning"></i> Error! There was a problem.</h4>'+
' '+html+''+
' </div>'+
' </div>'+
' </div> ');
}
}
});
});
</script>
SUBMIT_FORM.PHP
<?php session_start();
$json = array();
if ($_POST['text_box'] === NULL) {
$json['error'][] = "Please enter data in textbox.";
} else {
$textData = $_POST['text_box'];
}
if($json){ // If any Errors, return else, insert data into database.
echo json_encode($json);
exit;
} else {
// insert query that works is here.
echo json_encode($json);
exit;
}
?>