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.
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){
// 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);
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.