Ajax Random Number

Note: Random prices ($nn.nn) took too long to get a winner (too many digits). So, I’ve changed the demo to bid on fruit instead.

Every time you click on Banana, an Ajax call to the server generates a random fruit (from a set of 5) and says if you have a match or not.

Let’s bid Banana.
Click Banana above to start.

<div class="med-lg-size">Let's bid <span id="bid" class="clickable fancy-underline">Banana</span>.</div>
<div class="med-size"><span id="random">Click <strong>Banana</strong> above to start.</span></div>
// The Javascript part (front-end logic)
function add_ajax_random_script_footer()
{ ?>
        jQuery(document).ready(function($) {
            // This does the ajax request (The Call).
            $("#bid").click(function() {
            	// This is the variable we are passing via AJAX
				let bid = $("#bid").text();				
                    url: ajaxurl, // Already defined in pseudo functions.php
                    data: {
                        action: 'random_ajax_request', // This is our PHP function below
                        bid: bid // This is the variable we are sending via AJAX
                    success: function(data) {
                        // This outputs the result of the ajax request (The Callback)
                    error: function(errorThrown) {
<?php }
add_action('wp_footer', 'add_ajax_random_script_footer');

// The PHP (back-end logic)
function random_ajax_request()
	$fruit_array = array( "Apple", "Banana", "Mango", "Durian", "Strawberry");
	$pep_talk_phrases = array( 
		"Try again?", "C'mon, you can do it!", "Don't leave me hanging ...", "Hit me again.", "Don't give up.", "There's no try, only do ;-)", "Keep on truck'n.", "Getting closer.", "One more for grins :-)", "Think positive thoughts.", "I'll have another, please.", "No guts. No glory."
    // The $_REQUEST contains all the data sent via AJAX from the Javascript call
    if (isset($_REQUEST)) {
        $bid = $_REQUEST['bid'];
		$price = $fruit_array[ array_rand( $fruit_array ) ];
        if ($bid == $price) {
            $price .= '. ' . $price . ' is a winner!';
        } else {
			$price .= '. ' . $pep_talk_phrases[ array_rand( $pep_talk_phrases ) ];
        // Now let's return the result to the Javascript function (The Callback)
        echo $price;
    // Always die in functions echoing AJAX content
// This bit is a special action hook that works with the WordPress AJAX functionality.
add_action('wp_ajax_random_ajax_request', 'random_ajax_request');
add_action('wp_ajax_nopriv_random_ajax_request', 'random_ajax_request');

Want more? Check out the price bid demo that uses a random number API.

By mark

photographer ∙ writer ∙ web developer ∙ bali indonesia