0

I am trying to write an onclick function for a button on my website. Whenever that button is clicked a SQL query is executed and data will be fetched from the database. My requirement is to fetch the 2 records randomly every time the button is clicked, but I am getting the same output every time.

<input type="button" class="button" name="creat" id="bCreat" value="CREAT">

Onclick function

document.getElementById("bCreat").onclick = function creatBingo() 
            {
                    console.log("function clicked")

                    <?php

                    global $wpdb;
                    $result = $wpdb->get_results ( "SELECT * FROM bingo_tasks order by rand () limit 2" );
                    ?>

                document.getElementById("r0").innerHTML = '<?php echo $result[0]->task_name;?>';
                document.getElementById("r1").innerHTML = '<?php echo $result[1]->task_name;?>';
}

I tried to flush the value of $result by assigning it to 0 and null, but still i am getting the same value.

Is there way to get different results everytime the button is clicked?

Srikar Manthatti
  • 504
  • 2
  • 15
  • 1
    I think that your problem is right there in front of you. PHP is compiled, so when you go to put an hardcoded function javascript with some PHP inside, it became hardcoded into your webpage the instant it is loaded. So, right now, it just simply calls back the first 2 rows it load from Db when you load the page. I think u will see the difference if you just refresh the page. I think you need to use the admin-ajax with an api function to callback dynamically another PHP controller that does the query and return back your result via AJAX. – Davide I. May 13 '20 at 14:54
  • thanks Srikar for coming up with this interesting question! – zero May 14 '20 at 13:26

0 Answers0