Java
  Home arrow Java arrow Page 4 - Interacting with PHP for Server-side Data ...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVA

Interacting with PHP for Server-side Data Validation with AJAX
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 15
    2006-07-25

    Table of Contents:
  • Interacting with PHP for Server-side Data Validation with AJAX
  • Validating data on the server: building an input checking PHP class
  • Extending the functionality of the checking class: defining some additional methods
  • Assembling the pieces: completing the AJAX-driven checking application

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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.

       · Over the course of this final tutorial, you'll learn how to use a set of PHP...
       · A very good article - thank you. I get a parse error in the php-script :Parse...
       · Hello Andreas,Thank you for your kind comments on this article. Now, with...
       · I'm running PHP5 and I'm seeing the same error. Might be worth another look at...
       · Thank you for letting me know about your problem. I agree with you that it's...
       · I'm on php-5.1.6.Exactly the same error, whether via web server or directly.This...
       · class formValidator{public function __construct()...
       · With this (thanks to Lee Babin "Beginning Ajax with PHP" ,p.17)and minor changes...
       · Hello Monty,I'm glad to hear that now this application is finally working for...
       · I'm confused as there seems to be a file missing. I get an error "data_validator.php...
       · Thanks for the comments on my AJAX article. Concerning your question, you only need...
     

    JAVA ARTICLES

    - Deploying Multiple Java Applets as One
    - Deploying Java Applets
    - Understanding Deployment Frameworks
    - Database Programming in Java Using JDBC
    - Extension Interfaces and SAX
    - Entities, Handlers and SAX
    - Advanced SAX
    - Conversions and Java Print Streams
    - Formatters and Java Print Streams
    - Java Print Streams
    - Wildcards, Arrays, and Generics in Java
    - Wildcards and Generic Methods in Java
    - Finishing the Project: Java Web Development ...
    - Generics and Limitations in Java
    - Getting Started with Java Web Development in...







    © 2003-2010 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek