Programmatic POST Requests with JavaScript: A Functional Form Emulator - Building a functional script: listing the “getXMLHTTPObject()” and “sendRequest()” functions
(Page 2 of 5 )
Throughout the previous part of the series, I covered in detail these functions, so I won’t stop long explaining what they do. Essentially, the first function is responsible for instantiating XmlHttpRequest objects each time it’s invoked, while the second one makes http requests to a given server. Retaking the program’s flow, they’re listed below:
// 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;
}
// 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);
}
As I said before, the above functions implement actually the core logic of the program, because they provide the required functionality to use cross-browser XmlHttpRequest objects, and send http requests to a specific host as well. However, I explained previously that the program was capable of performing additional tasks, such as getting data about the form to be emulated. Thus, over the next section, I’ll define the functions tasked with obtaining the form’s source code, as well as its action attribute along with its field names.
Next: Getting the form’s (X)HTML markup: defining the “getFormCode()” function >>
More JavaScript Articles
More By Alejandro Gervasio