JavaScript Remote Scripting: An AJAX-based Random Code Generator in Action
In this article, Alejandro Gervasio finishes his discussion of creating a random code generator. Going beyond the core functions, he defines the remaining JavaScript functions needed to turn the random code generator into a functional program.
JavaScript Remote Scripting: An AJAX-based Random Code Generator in Action - Putting the pieces together: showing the application’s complete code (Page 6 of 6 )
For you to have the complete code that integrates the application, first I’ll list the “requester.htm” file, including some additional CSS rules as well the structural (X)HTML markup. Here is the pertinent file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>AJAX-BASED RANDOM CODE GENERATOR</title> <script type="text/javascript"> // initialize XMLHttpRequest object var xmlobj=null; // 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); } } } // create data container function createDataContainer(elem,data){ if(elem.getElementsByTagName('div')[0]){return}; // create containing <div> var div=document.createElement('div'); div.className='container'; // assign custom attribute div.setAttribute('active','true'); // create form var f=document.createElement('form'); f.setAttribute('action','checkvote.php'); f.setAttribute('method','post'); // create input box element var inp=document.createElement('input'); inp.setAttribute('type','text'); inp.setAttribute('name','challenge'); inp.setAttribute('maxlength','4'); inp.setAttribute('size','4'); inp.className='midchars'; // create submit button var btn=document.createElement('input'); btn.setAttribute('type','submit'); btn.setAttribute('name','vote'); btn.setAttribute('value','Go!'); // create paragraph & include challenge value var pc=document.createElement('p'); pc.className='largechars'; pc.appendChild(document.createTextNode(data)); // create paragraph to display instructions var pl=document.createElement('p'); pl.className='smallchars'; pl.appendChild(document.createTextNode('Enter the above number to rate this article (case insensitive)')); // add elements to form f.appendChild(pc); f.appendChild(pl); f.appendChild(inp); f.appendChild(btn); // add form to div element div.appendChild(f); // add div to document tree elem.parentNode.appendChild(div); } // create rating links function createLinks(){ var ps=document.getElementsByTagName('p'); if(!ps){return}; for(var i=0;i<ps.length;i++){ // create <span> elements var sp=document.createElement('span'); // create <a> elements var a=document.createElement('a'); a.setAttribute('href','#'); a.setAttribute('title','Rate this article!'); a.appendChild(document.createTextNode('Rate this article!')); sp.appendChild(a); // assign 'onclick' event handler to <span> elements sp.onclick=function(){ sendRequest(this,'process_input1.php'); } ps[i].appendChild(sp); } } // remove active node function removeActiveNodes(){ var divs=document.getElementsByTagName('div'); for(var i=0;i<divs.length;i++){ if(divs[i].getAttribute('active')=='true'){ divs[i].parentNode.removeChild(divs[i]); } } } // execute program when page is loaded window.onload=function(){ // check if browser is DOM compatible if(document.getElementById&&document. getElementsByTagName&&document.createElement){ // create button createLinks(); } } </script> <style type="text/css"> h1 { font: bold 24px Tahoma, Arial; color: #000; } h2 { font: bold 11px Verdana, Arial; color: #00b; } p { font: normal 11px Verdana, Arial; color: #000; } p.largechars { font: bold 18px Tahoma, Arial; color: #000; } p.smallchars { font: bold 11px Tahoma, Arial; color: #000080; } div.container { background: #eee; border: 1px solid #ccc; width: 200px; padding: 5px; margin-top: 10px; } span { margin-left: 10px; } a:link,a:visited { color: #00f; } a:hover { color: #f00; } .midchars { font: bold 14px Tahoma, Arial; color: #000; } </style> </head> <body> <h1>Article Listing</h1> <h2>Building Object-Oriented Database Interfaces in PHP: Processing Data through Data Access Objects</h2> <p>With websites now featuring full-blown dynamic applications that link to databases, data accessing has become a critical process…</p> <h2>Building Object-Oriented Database Interfaces in PHP: Abstracting Database Tables</h2> <p>Welcome to part two of the series "Building Object-Oriented Database Interfaces in PHP." In the previous article...</p> <h2>Object Interaction in PHP: Introduction to Composition</h2> <p>Composition is an important concept in PHP. It occurs when an object creates another object; that is, the first object completely possesses the second object. In this article...</p> <h2>Object Interaction in PHP: Introduction to Aggregation</h2> <p>In this second part of his series, Alejandro Gervasio gets a little more technical with the basics of Aggregation. He begin...</p> </body> </html>
Having listed the “requester.htm” file, here’s how the “process_input.php” file looks:
<?php function getRandomString($length=4){ if(!is_int($length)||$length<1){ trigger_error('Invalid length for random string'); exit(); } $chars="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $randstring=''; $maxvalue=strlen($chars)-1; for($i=0;$i<$length;$i++){ $randstring.=substr($chars,rand(0,$maxvalue),1); } return $randstring; } // start or resume session session_start(); // store challenge value in session variable $_SESSION['challenge']=getRandomString(); // send challenge value to client echo $_SESSION['challenge']; ?>
And finally, considering that each time a visitor submits the provided random code for rating an article, below is the sample “checkvote.php” file, which basically checks to see whether the user has entered the correct value:
<?php session_start(); $message=(strtolower($_POST['challenge'])==strtolower($_SESSION ['challenge']))?'The entered code is correct!':'The entered code is not correct! Please go back and try again.'; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Verifying code...</title> <style type="text/css"> h1 { font: bold 24px Tahoma, Arial; color: #000; } </style> </head> <h1><?php echo $message ?></h1> <body> </body> </html>
As you can see, this checking file simply determines whether the code submitted by the user is correct, by comparing this value with the “challenge” session variable created on the “process_input.php” file. In either case, a basic informative message is displayed, informing the user of the entry’s result. Obviously, this is a crude implementation of a checking routine. From this point on you can develop your own application for processing user data, either for rating articles, building a polling system or whatever program you want to incorporate into your website. Certainly, possibilities are numerous.
Wrapping up
The work is done. Over this tutorial I’ve demonstrated how to build a fully-functional random code generator, particularly applied to an article-rating system by using AJAX. From the great variety of web applications I’ve picked out this example for illustrating the great capabilities of JavaScript remote scripting.
The best thing about remote scripting is its versatility. In another series, I will focus on rewriting the application that you just saw, this time using only fully-standard DOM constructs. Want to know more? Wait for the upcoming new series!
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.