$errors = array(); // array to hold validation errors $data = array(); // array to pass back data// validate the variables ======================================================if (empty($_POST['name']))$errors['name'] = 'Name is required.';if (empty($_POST['superheroAlias']))$errors['superheroAlias'] = 'Superhero alias is required.';// return a response ===========================================================// response if there are errorsif ( ! empty($errors)) {// if there are items in our errors array, return those errors$data['success'] = false;$data['errors'] = $errors;} else {// if there are no errors, return a message$data['success'] = true;$data['message'] = 'Success!';}// return all our data to an AJAX callecho json_encode($data);
...<script>$(document).ready(function() {// process the form$(&#39;form&#39;).submit(function(event) {// remove the past errors$(&#39;#name-group&#39;).removeClass(&#39;has-error&#39;);$(&#39;#name-group .help-block&#39;).empty();$(&#39;#superhero-group&#39;).removeClass(&#39;has-error&#39;);$(&#39;#superhero-group .help-block&#39;).empty();// remove success messages$(&#39;#messages&#39;).removeClass(&#39;alert alert-success&#39;).empty();// get the form datavar formData &#61; {&#39;name&#39; : $(&#39;input[name&#61;name]&#39;).val(),&#39;superheroAlias&#39; : $(&#39;input[name&#61;superheroAlias]&#39;).val()};// process the form$.ajax({type : &#39;POST&#39;,url : &#39;process.php&#39;,data : formData,dataType : &#39;json&#39;,success : function(data) {// log data to the console so we can seeconsole.log(data);// if validation fails// add the error class to show a red input// add the error message to the help block under the inputif ( ! data.success) {if (data.errors.name) {$(&#39;#name-group&#39;).addClass(&#39;has-error&#39;);$(&#39;#name-group .help-block&#39;).html(data.errors.name);}if (data.errors.superheroAlias) {$(&#39;#superhero-group&#39;).addClass(&#39;has-error&#39;);$(&#39;#superhero-group .help-block&#39;).html(data.errors.superheroAlias);}} else {// if validation is good add success message$(&#39;#messages&#39;).addClass(&#39;alert alert-success&#39;).append(&#39;
&#39;
&#43; data.message &#43; &#39;
&#39;);}}});// stop the form from submitting and refreshingevent.preventDefault();});});script>...