I need a script (php, java, etc.) to generate a random four-digit, alphanumeric number at the press of a button. It should be able to be added to a webpage and display the result next to the link/button in standard text. Nothing fancy. Respond here or PM offers/example. Thanks-
<?php if (!empty($_POST)) { $random_string = random_string(4); } else { $random_string = ''; } function random_string($len, $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') { $string = ''; for ($i=0; $i<$len; $i++) { $pos = mt_rand(0, strlen($chars)-1); $string .= $chars{$pos}; } return $string; } ?> <html> <body> <?php if ($random_string): ?> The random number is: <?php echo $random_string; ?> <?php endif; ?> <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" style="display:inline"> <input type="submit" name="submit" value="Generate" /> </form> </body> </html> Code (markup):
test.php <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script> <body> <p>Random number: <span id="random_number"></span> <a href="#" onclick="$('#random_number').load('ajax.php');return false;">load</a></p> </body> </html> Code (markup): ajax.php <?php function random_string($len, $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') { $string = ''; for ($i=0; $i<$len; $i++) { $pos = mt_rand(0, strlen($chars)-1); $string .= $chars{$pos}; } return $string; } echo random_string(4); ?> Code (markup):
Though now that I think about it, this could just as easily be done in regular javascript It's because you asked for a php solution first that I did not consider that. Ehh, it works just the same really.
I know this thread is old, but can anyone tell me how to generate this random number into a text field via the ajax script?