JavaScript Remote Scripting: Building an AJAX-based Random Code Generator - Implementing the core logic of the script: defining the “statusChecker()” function
(Page 3 of 4 )
Surely, you may have noticed that once an XMLHttpRequest object has been instantiated, the “stateChecker()” function is tied to the “onreadystatechange” event handler, in order to verify the progress of an http request. Very similar in its definition to previous examples, this function is defined as follows:
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);
}
}
}
As you can see, the above code snippet speaks for itself. After the request has been successfully completed, that is the “readyState” property has a value of “200”, the function calls in sequence to the “removeActiveNodes()” and “createDataContainer()” functions. Don't be concerned about them now, since they’ll be explained shortly.
For the moment, I’ll say that the first function is tasked with removing from the document tree any input box that might be active when a user clicks on a rating link, while the second function is responsible for building the corresponding input boxes, as well as displaying the random codes that you saw right at the second screenshot.
By returning to the flow of the script, there are some additional points that should be noticed with reference to the “stateChecker()” function. First, despite its extreme simplicity, it really implements the driving logic of the program, because each request is made in asynchronous mode. By delegating program control to a function that checks for the progress of http requests, it’s fairly easy to build the overall programming logic around this function, without the need to implement more complex control blocks.
At this point, I’ve explained in detail the programming logic of the whole application, as well as the tasks of some relevant program functions, such as “sendRequest()” and “stateChecker()”. Keeping this concept in mind, the next step will be taking a look at the “removeActiveNodes()” function, so you can see how the program avoids the circumstance of having an user trying to rate multiple articles through the same request.
Next: Avoiding simultaneous data submission: coding the “removeActiveNodes()” function >>
More JavaScript Articles
More By Alejandro Gervasio