JavaScript Remote Scripting: An AJAX-based Random Code Generator in Action - Looking at existing functions: the “sendRequest()” and “stateChecker()” functions at a glance
(Page 2 of 6 )
A natural place to continue building the code generating application is listing the relevant functions that were previously defined and explained. Keeping this idea in mind, here is the list of the first two functions, “sendRequest()” and “statusChecker()”, as I wrote them originally:
// send http request
function sendRequest(elem,file){
// check for existing requests
if(xmlobj!=null&&xmlobj.readyState!=0&&xmlobj.readyState!=4){
xmlobj.abort();
}
try{
// instantiate object for Mozilla, Nestcape, etc.
xmlobj=new XMLHttpRequest();
}
catch(e){
try{
// instantiate object for Internet Explorer
xmlobj=new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e){
// Ajax is not supported by the browser
xmlobj=null;
return false;
}
}
// assign state handler
xmlobj.onreadystatechange=function(){
stateChecker(elem);
}
// open socket connection
xmlobj.open('GET',file,true);
// send request
xmlobj.send(null);
}
// check request status
function stateChecker(elem){
// if request is completed
if(xmlobj.readyState==4){
// if status == 200 display text file
if(xmlobj.status==200){
// remove active nodes
removeActiveNodes();
// create data container & display challenge value
createDataContainer(elem,xmlobj.responseText);
}
else{
alert('Failed to get response :'+ xmlobj.statusText);
}
}
}
Since the functions above were covered in detail in the previous part of the series, it’s pointless to explain the logic of each one here. For the sake of completeness, allow me to say that the first one takes care of sending GET requests in asynchronous mode, while the task of the second one consists of checking the status of each request.
Of course, by placing the functions in the context of the article-rating example that you saw in the previous part, what I’ve done is code a function that will fetch a file on the server, each time a user clicks on a link for rating a given article. On its side, the server will generate a four-digit random code that will be sent back to the client and displayed to the user. Finally, the visitor should enter this random code, in order to access the page where he/she can actually rate the pertinent article.
As I explained before, each time a visitor tries to rate an article, an input box is created on the fly and displayed right at the bottom of the article heading section, so the four-digit random code sent by the server can be typed by the user. The entire process for creating dynamic input boxes and showing random codes is performed by the “createDataContainer()” function, which will be reviewed over the next few lines.
Next: Displaying random codes: defining the “createDataContainer()” function >>
More JavaScript Articles
More By Alejandro Gervasio