Home arrow JavaScript arrow Page 2 - Programmatic POST Requests with JavaScript: Form Emulator in Action
JAVASCRIPT

Programmatic POST Requests with JavaScript: Form Emulator in Action


In the fourth and final part of our series, we examine the form emulator we built in the third part in the context of a practical example that puts the program to work. The form emulator can be used as a simple testing bed to help you build more robust and safer Web applications.

Author Info:
By: Alejandro Gervasio
Rating: 5 stars5 stars5 stars5 stars5 stars / 23
August 03, 2005
TABLE OF CONTENTS:
  1. · Programmatic POST Requests with JavaScript: Form Emulator in Action
  2. · The first step in coding the example: listing the program’s functions
  3. · The second step in coding the example: defining the sample files
  4. · The third step in coding the example: running the form emulator program
  5. · The complete form emulator script: listing the full source code

print this article
SEARCH DEVARTICLES

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.


blog comments powered by Disqus
JAVASCRIPT ARTICLES

- Project Nashorn to Make Java, JavaScript Wor...
- JavaScript Virus Attacks Tumblr Blogs
- Google Releases Stable Dart Version, JavaScr...
- Khan Academy Unveils New JavaScript Learning...
- Accessing Nitro? There`s an App for That
- JQuery 2.0 Leaving Older IE Versions Behind
- Fastest JavaScript Engine Might Surprise You
- Microsoft Adjusting Chakra for IE 10
- Brendan Eich: We Don`t Need Google Native Cl...
- An Overview of JavaScript Statements
- An Overview of JavaScript Operators
- Overview of JavaScript Variables
- More of the Top jQuery Social Plugins
- The Top jQuery Social Plugins
- More of the Top jQuery Slider Plugins

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials