JS:
$('#submitButtton').click(function(){
$.ajax({
dataType: "json",
type: 'POST',
url: url/to/ajax-results.php',
data: { $('form#my-form').serialize(); }
}).done(function(data){
if(data.response == 'error') {
$('#results').html('<div class="error">'+data.report+'</div>');
$('#results').show();
return false;
}
window.location.href = data.redirect
});
});
PHP:
<?php
$errors = array();
$val1 = $_POST['val1'];
if(empty($val1)) {
$errors[] = 'val1 cannot be empty';
}
if(count($errors) > 0) {
echo json_encode(array(
'response' => 'error',
'report' => 'send your errors array, or custom error message'
));
exit();
} else {
echo json_encode(array(
'response' => 'ok',
'redirect' => 'http://www.domain.com/url/to/redirect'
));
exit();
}
?>