JavaScript
  Home arrow JavaScript arrow Page 5 - Developing the Client-Side Code for Server...
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 
Sun Developer Network 
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? 
JAVASCRIPT

Developing the Client-Side Code for Server-Side Data Validation with AJAX
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 11
    2006-07-18

    Table of Contents:
  • Developing the Client-Side Code for Server-Side Data Validation with AJAX
  • Triggering HTTP requests in the background: meet the world of requester objects
  • Processing server responses: defining the “displayErrorMessage()” function
  • Controlling the flow of data validation: defining the “initializeForm()” function
  • Integrating the client-side application layer: listing all of the JavaScript functions

  • 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


    Developing the Client-Side Code for Server-Side Data Validation with AJAX - Integrating the client-side application layer: listing all of the JavaScript functions


    (Page 5 of 5 )

    As I mentioned in the previous section, below I listed all the JavaScript functions that comprise the client-side application layer. Please take a look:

      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('validator1.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();
        }
      }

    As you can see, that’s all the JavaScript functions that compose this AJAX-drive program. However, the prior code listing would be rather incomplete if I didn't show you the corresponding (X)HTML markup and the CSS declarations that also play a relevant role, in order to get the application working. Therefore, here they are:

      <style type="text/css">
      body {
        margin: 0;
        padding: 0;
      }
      p{
        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="nextpage.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>

    To wrap up

    In this second article of the series, I provided you with the complete set of JavaScript functions, aimed at sending HTTP requests in the background, as well as displaying error messages and controlling the flow of data validation. If you’re used to working with requester objects, then all these concepts should be easy for you to grasp.

    Over the last tutorial, I’ll develop the PHP routines, tasked with validating several types of user-supplied input, in order to get the AJAX-driven form validation program completed. If you wish to know how this story ends, don’t miss the last chapter!


    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.

       · In this second article of the series, all the JavaScript functions that compose the...
       · where to find the third part of Server-Side Data Validation with AJAX? I cann't find...
       · Thank you for your interest on my AJAX article. You can read the last part...
     

    JAVASCRIPT ARTICLES

    - Using Click Interceptions with a Database-Dr...
    - Using JavaScript Click Interceptions in an I...
    - Using Click Interceptions with JavaScript
    - QuickSort in Action
    - Quicksort
    - Using Mod_Security to Protect Your Server
    - Detecting and Countering Server Intrusions
    - Securing Your Web Server
    - Building a Secure Web Server
    - Protecting the Server
    - Book Review: Learning the Yahoo! User Interf...
    - Dynamically Generate a Selection List in a R...
    - Intergrate DWR into Your Java Web Application
    - Detect Browser Compatibility with the Reques...
    - Using the EXT JS Date Picker Widget






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
    Stay green...Green IT