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 - Server-side processing: generating four-digit random codes with PHP (Page 5 of 6 )
As you saw when I explained the function for generating rating links, each <a> element was responsible for triggering a GET request, in order to fetch the “process_input.php” file and obtain the corresponding random code. Considering this situation, let’s have a look at the structure of this file, which contains a few lines of PHP code. Its source code is as follows:
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'];
As you can see, I’ve defined a simple PHP function for generating four-digit random strings. After defining the pertinent function, I’ve stored this value in a “challenge” session variable, which will be utilized by the server to determine whether the user has entered the correct code when proceeding to rate an article.
Of course, the most interesting thing here is how the server sends back the random value to the client. By simply echoing this value, the random code can be obtained through the “responseText” property that belongs to the “XMLHttpRequest object, and displayed accordingly.
Having provided you with all the proper explanations of each function involved in the implementation of the code generating application, the next thing to be done is to show the full source code for each file that integrates the program. Therefore, join me in the next few lines to see how the complete program code looks.