0

I've been trying to get this script to work. I made a PHP random number generator and I'm trying to get it to feed to my main php page and update a div with the number generated whenever I push a button.

It works, kind of. It generates the number one time and no matter how many times you push the button afterwards, it doesn't update the element anymore.

I thought that I might have to clear the element first, so I added that in and it still doesn't work. Below is my code for index.php and randomRoller.php

<?php
include("./includes/randomRoller.php")
?>
<style type="text/css">
#cookies {
    width: 50px;
    height: 100px;
    background-color: #000000;
    color: #ffffff;
}
#bunnies {
    width: 100px;
    height: 500px;
    background-color: #555555;
    color: red;
}
</style>
<script>
function roll() {
    document.getElementById('bunnies').innerHTML = '';
    document.getElementById('bunnies').innerHTML = '<?php echo(roll()) ?>';
}
</script>
<button type="button" onClick="roll()">Test</button>
<div id="cookies">
</div>
<br>
<br>
<div id="bunnies">
</div>

./includes/randomRoller.php

<?php
    function roll() {
        return rand(1 , 200);
    }
?>

Any hints or advice you can give me would be much appreciated.

  • Open generated html and see what you have there – u_mulder Sep 25 '16 at 17:56
  • Possible duplicate of [What is the difference between client-side and server-side programming?](http://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – u_mulder Sep 25 '16 at 17:56
  • It generates the number one time cause there is a single call to roll() in your page. Use ajax to fetch a new random number each time the button is pressed – Andreas Sep 25 '16 at 17:57

1 Answers1

0

I do not know if it crucial that it is a separate page for generating the number, if not you can use JS for creating a random number, like so:

<script>
function roll() {
    var bunnies = document.getElementById('bunnies')
    bunnies.innerHTML = Math.floor((Math.random() * 10) + 1);
}
</script>
<button type="button" onClick="roll()">Test</button>

You can use AJAX (jQuery library) to load number from another page:

function roll() {
  $.get( "/includes/randomRoller.php", function( data ) {
    $( "#bunnies" ).html( data );
  });
}
Marcin
  • 1,488
  • 1
  • 13
  • 27