JavaScript
  Home arrow JavaScript arrow Page 2 - Programmatic POST Requests with JavaScript...
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

Programmatic POST Requests with JavaScript: Form Emulator in Action
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 12
    2005-08-03

    Table of Contents:
  • Programmatic POST Requests with JavaScript: Form Emulator in Action
  • The first step in coding the example: listing the program’s functions
  • The second step in coding the example: defining the sample files
  • The third step in coding the example: running the form emulator program
  • The complete form emulator script: listing the full source code

  • 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


    Programmatic POST Requests with JavaScript: Form Emulator in Action - The first step in coding the example: listing the program’s functions


    (Page 2 of 5 )

    Before I start writing the example, I’ll provide you with all of the functions that integrate the form emulator program. Doing so, you’ll have at hand the source code just in case you want to study it and make some changes for adapting it to your own needs. Thus, below is the full listing for the program’s functions, beginning with the “getXMLHTTPObject()” function:

    // function getXMLHTTPObject

    function getXMLHTTPObject(){

        //instantiate new XMLHttpRequest object

        var objhttp=(window.XMLHttpRequest)?new XMLHttpRequest
    ():new ActiveXObject('Microsoft.XMLHTTP');

        if(!objhttp){return};

        // assign event handler

        objhttp.onreadystatechange=displayStatus;

                // return XMLHttpRequest object

        return objhttp;

    }

    Then, here is the list for the “sendRequest()” function:

    // function sendRequest

    function sendRequest(url,data,method,mode,header){

        // set default values

        if(!url){url='default_url.htm'};

        if(!data){data='defaultdata=defaultvalue'};

        if(!method){method='post'};

        if(!mode){mode=true};

        if(!header){header='Content-Type:application/x-www-form-
    urlencoded; charset=UTF-8'};

        // get XMLHttpRequest object

        objhttp=getXMLHTTPObject();

        // open socket connection

        objhttp.open(method,url,mode);

        // set http header

        objhttp.setRequestHeader(header.split(':')
    [0],header.split(':')[1]);

        // send data

        objhttp.send(data);

    }

    Next, the source code for the “displayStatus()” function:

    // function displayStatus

    function displayStatus(){

        // check XMLHttpRequest object status

        if(objhttp.readyState==4){

            // create paragraph elements

            var parStat=document.createElement('p');

            var parText=document.createElement('p');

            var parResp=document.createElement('p');

            // assign ID attributes

            parStat.id='status';

            parText.id='text';

            parResp.id='response';

            // append text nodes

            parStat.appendChild(document.createTextNode
    ('Status : '+objhttp.status));

            parText.appendChild(document.createTextNode('Status
    text : '+objhttp.statusText));

            parResp.appendChild(document.createTextNode
    ('Document code : '+objhttp.responseText));

            // insert <p> elements into document tree

            document.body.appendChild(parStat);

            document.body.appendChild(parText);

            document.body.appendChild(parResp);

        }

    }

    The list is not finished yet. Below is the definition for the “getFormCode()” function:

    // function getFormCode

    function getFormCode(){

        // create <div> container

        var fdiv=document.createElement('div');

        // append <div> container into document tree

        document.body.appendChild(fdiv);

        // get page code

        var html=objhttp.responseText;

        // insert form code into document tree

        fdiv.innerHTML=html.substring(html.search
    (/<form\b/),html.search(/<\/form>/));

        // hide form from being displayed

        fdiv.style.display='none';

    }

    The next few lines list the functions tasked with obtaining information about the targeted form:

    // function getFormVariables

    function getFormVariables(){

        var formvars='';

        var childElements=document.getElementsByTagName('form')
    [0].childNodes;

        for(var i=0;i<childElements.length;i++){

            if(/(INPUT|TEXTAREA|SELECT)/.test(childElements[i].nodeName)){

        // check if field name contains the string 'email'  formvars+=(/mail/.test(childElements[i].getAttribute
    ('name')))?childElements[i].getAttribute('name')
    +'='+getRandomEmail()+'&':childElements[i].getAttribute
    ('name')+'='+getRandomValue()+'&';

            }

        }

        formvars=formvars.substring(0,formvars.length-1);

        return formvars;

    }

    // function getFormAction

    function getFormAction(){

        var formaction=document.getElementsByTagName('form')
    [0].getAttribute('action');

        if(!formaction){return};

        return formaction;

    }

    Finally, the list ends with the definition for the “getRandomValue()” and “getRandomEmail()” functions:

    // function getRandomValue

    function getRandomValue(){

        var chars='abcdefghiklmnopqrstuvwxyz0123456789';

        var rndstring='';

        var strlength=Math.floor(Math.random()*8)+2;

        for(var i=0;i<strlength;i++){

            var rndvalue=Math.floor(Math.random()*chars.length);

            rndstring+=chars.substring(rndvalue,rndvalue+1);

        }

        return rndstring;

    }

    // function getRandomEmail

    function getRandomEmail(){

        return 'johndoe'+getRandomValue()+'@'+getRandomValue()+'.com';

    }

    Now that you know how each relevant function looks, the next step consists of coding two simple files. The first one will be the hypothetical form page targeted by the form emulator script, while the second one will be a generic file that represents the URL to where the form is pointed (the form’s action). As you’ll see shortly, despite the simplicity of the sample files, the example is useful for demonstrating in practical terms how a common post form may be easily emulated.

    More JavaScript Articles
    More By Alejandro Gervasio


       · The final part of the series implements a fully-functional form emulator, which...
     

    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