Interacting with PHP for Server-side Data Validation with AJAX
Looking for new and creative ways to empower your AJAX-driven Web applications? Then you’ve landed at the right place. Welcome to the final part of the series “Server-side Data Validation with AJAX.” In three tutorials, this series demonstrates how to build a simple form checking system which uses AJAX to performing server-side validation on the data supplied by users.
Interacting with PHP for Server-side Data Validation with AJAX - Assembling the pieces: completing the AJAX-driven checking application (Page 4 of 4 )
As I mentioned earlier, in this section I'm going to show you how the complete AJAX-based form checking application looks. It will give you a better idea of how the JavaScript functions that I created over the course of the second article, and the respective PHP validation class perform a mutual interaction.
That said, I'll begin listing the full client-side code, encapsulated within a file that I called "ajax_validator.htm" (of course you can name it anything else), which looks like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1- transitional.dtd"> <html> <head> <title>AJAX-BASED FORM VALIDATOR</title> <meta http-equiv="Content-Type" content="text/html; charset=iso- 8859-1" /> <script language="javascript"> var errors=new Array(); // send http requests function sendHttpRequest(url,callbackFunc,respXml){ var xmlobj=null; try{ xmlobj=new XMLHttpRequest(); } catch(e){ try{ xmlobj=new ActiveXObject("Microsoft.XMLHTTP"); } catch(e){ alert('AJAX is not supported by your browser!'); return false; } } xmlobj.onreadystatechange=function(){ if(xmlobj.readyState==4){ if(xmlobj.status==200){ respXml?eval (callbackFunc+'(xmlobj.responseXML)'):eval (callbackFunc+'(xmlobj.responseText)'); } } } // open socket connection xmlobj.open('GET',url,true); // send http header xmlobj.setRequestHeader('Content-Type','text/html; charset=UTF-8'); // send http request xmlobj.send(null); } // initialize form and assign events function initializeForm(){ document.getElementsByTagName('form')[0].elements [3].disabled=true; var elems=document.getElementsByTagName('form')[0].elements; if(!elems){return}; for(var i=0;i<elems.length;i++){ // check for 'required' attribute if(elems[i].getAttribute('required')){ elems[i].onblur=function(){ // validate current field sendHttpRequest('ajax_validator.php? field='+this.getAttribute('name') +'&value='+this.value+'&method='+this.getAttribute('required') +'&message='+this.getAttribute ('title'),'displayErrorMessage',false); } } } } // display error messages function displayErrorMessage(serverResponse){ var elemkey=serverResponse.split('|')[0]; var errormsg=serverResponse.split('|')[1]; var counter=0; var msgcont=document.getElementById('msgcontainer'); if(msgcont){msgcont.parentNode.removeChild(msgcont)}; var msgcont=document.createElement('div'); msgcont.setAttribute('id','msgcontainer'); // assign error values to error counters errors[elemkey]=(errormsg==' ')?0:1; // count total errors for(var i in errors){if(errors[i]){counter++}}; var btn=document.getElementsByTagName('form')[0].elements[3]; if(!counter){ // if no errors were found enable submit button btn.disabled=false; var errormsg='Data is Ok. Now submit the form, please.'; } else{ // if errors were found enable submit button & display error message btn.disabled=true; } msgcont.appendChild(document.createTextNode(errormsg)); document.getElementById('formcontainer').appendChild (msgcont)
} // run 'initializeForm()' function when page is loaded window.onload=function(){ // check if browser is DOM compatible if(document.createElement&&document.getElementById &&document.getElementsByTagName){ initializeForm(); } } </script> <style type="text/css"> body { margin: 0; padding: 0; } h1{ text-align: center; font: bold 24px Arial, Tahoma; color: #000; } p{ font: bold 12px Arial, Tahoma; color: #000; text-align: right; margin-right: 50px; } #formcontainer{ width: 350px; height: 300px; padding: 5px; background: #efdfff; border: 1px solid #ccc; margin-left: auto; margin-right: auto; } #msgcontainer{ width: 300px; height: 30px; padding: 10px; font: bold 12px Arial; color: #f00; text-align: center; } .inputbox{ width: 200px; font: normal 12px Arial; color: #000; } .formbutton{ width: 100px; font: normal 12px Arial, Tahoma; color: #000; } </style> </head> <body> <div><p>AJAX-BASED FORM VALIDATOR</p></div> <div id="formcontainer"> <form method="post" action="data_validator.php"> <p>First Name <input name="fname" type="text" required="Empty" class="inputbox" title="Enter your First Name (at least 8 characters)" /></p> <p>Last Name <input name="lname" type="text" required="Empty" class="inputbox" title="Enter your Last Name (at least 8 characters)" /></p> <p>Email <input name="email" type="text" required="EmailWin" class="inputbox" title="Enter a valid email address" /></p> <p><input type="submit" value="Send Data" class="formbutton" /></p> </form> <div> </body> </html>
After listing the entire client-side code of the AJAX application, here you have the full definition of the "formValidator" class along with a simple implementation of it, which I've included within a file called "ajax_validator.php." Please take a look:
<?php class formValidator{ public function __construct(){ $this->method=$_GET['method']; $this->field=$_GET['field']; $this->value=$_GET['value']; $this->message=$_GET['message']; } // validate empty field public function validateEmpty ($field,$value,$errorMessage,$min=8,$max=32){ if(!isset($value)||trim($value)==''||strlen($value) <$min||strlen($value)>$max){ return $field.'|'.$errorMessage; } else{ return $field.'| '; } } // validate integer field public function validateInt($field,$value,$errorMessage){ if(!isset($value)||!is_numeric($value)||intval($value)! =$value){ return $field.'|'.$errorMessage; } else{ return $field.'| '; } } // validate numeric field public function validateNumber($field,$value,$errorMessage){ if(!isset($value)||!is_numeric($value)){ return $field.'|'.$errorMessage; } else{ return $field.'| '; } } // validate if field is within a range public function validateRange ($field,$value,$errorMessage,$min=1,$max=99){ if(!isset($value)||$value<$min||$value>$max){ return $field.'|'.$errorMessage; } else{ return $field.'| '; } } // validate alphabetic field public function validateAlphabetic ($field,$value,$errorMessage){ if(!isset($value)||!preg_match("/^[a-zA-Z]+$/",$value)){ return $field.'|'.$errorMessage; } else{ return $field.'| '; } } // validate alphanumeric field public function validateAlphanum($field,$value,$errorMessage) { if(!isset($value)||!preg_match("/^[a-zA-Z0-9] +$/",$value)){ return $field.'|'.$errorMessage; } else{ return $field.'| '; } } // validate email public function validateEmail($field,$value,$errorMessage){ if(!isset($value)||!preg_match("/.+@.+..+./",$value)||! checkdnsrr(array_pop(explode("@",$value)),"MX")){ return $field.'|'.$errorMessage; } else{ return $field.'| '; } } // validate email (Windows systems) public function validateEmailWin($field,$value,$errorMessage) { if(!isset($value)||!preg_match("/.+@.+..+./",$value)||! $this->windnsrr(array_pop(explode("@",$value)),"MX")){ return $field.'|'.$errorMessage; } else{ return $field.'| '; } } // private method 'windnsrr()' for Windows systems private function windnsrr($hostName,$recType=''){ if(!empty($hostName)){ if($recType=='')$recType="MX"; exec("nslookup -type=$recType $hostName",$result); foreach($result as $line){ if(preg_match("/^$hostName/",$line)){ return true; } } return false; } return false; } // call validation method on the fly public function callValMethod(){ eval("echo $this->validate".$this->method."('".$this- >field."','".$this->value."','".$this->message."');"); } } // instantiate 'formValidator' object try{ $formVal=new formValidator(); // call validation method on the fly $formVal->callValMethod(); } catch(Exception $e){ echo $e->getMessage(); exit(); } ?>
That's all you need to get the AJAX-based form validation application working. As usual, feel free to modify the source code shown here, in order to fit your specific requirements.
Final thoughts
Over this series, I provided you all the corresponding explanations and code samples in order to construct a simple yet powerful form checking application that uses the functionality provided by AJAX for performing server-side data validation via HTTP requests triggered in the background.
If AJAX is currently an important part of your Web development toolbox, then the application you learned here may find a place into your existing or future projects. See you in the next Web development tutorial!
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.