I have a button that when I click it should generate a random number using ajax ( It needs to be processed by PHP in real world application).

This works fine except that every time the button is clicked it produces the same random number. Why doesn't the ajax call run the php rand function new each time?


function rand_load_scripts() {
    //create an object that is accessible from our Javascript The name of this object is the second parameter, rand_script_vars
    wp_enqueue_script('rand-script', plugin_dir_url( __FILE__ ) . 'assets/rand-script.js');
    //an array of variables to pass to javascript.
    wp_localize_script('rand-script', 'rand_script_vars', array(
            'get_prices' => rand()
add_action('wp_enqueue_scripts', 'rand_load_scripts');


jQuery(document).ready(function($) {
        $('#rand_button').on('click', function() {
            console.log( rand_script_vars.get_prices );

  • 1
    For me ut looks like you just genetate the random number and set the js value on page load. There is nonajax call running the php on click. After refreshing the page the random number should be different – Luckyfella Jun 19 at 11:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.