I am making a website where you can random throw dices. First I made the function to throw in JavaScript. Now I want it in PHP. Everything works, but the whole Site is always reloading if I try to throw it in PHP.
So I read I must use AJAX. But it doesen't work. The Site uses jQuery, so it should be an easy task. I tried it for hours but it doesen't work. Can you see where the problem is?
The code is as following:
<form name="imageForm">
<table border=0>
<tr>
<td>
<img src="<?php echo $randomImage; ?>" name="canvas" width="50%" height="auto"/>
</td>
</tr>
<tr>
<td>
<br>
<form method="post"><input type="submit" name="random" id="randomImage" value="random" class="btn type--uppercase"/><br/></form>
<a onclick="displayImage();" class="btn btn--lg type--uppercase" href="#random"><span class="btn__text">
Random Dice Roll
</span>
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
</div>
</section>
<!-- Scripts -->
<script>
function displayImage(){
$.ajax({
url: "random.php",
success: function(data){
$('img[name="canvas"]').attr('src', data);
}
});
return false;
}
</script>
<script src="js/parallax.js"></script>
<script src="js/smooth-scroll.min.js"></script>
<script src="js/scripts.js"></script>
<script src="js/random-dice-6-sides/random.js"></script>
</body>
</html>
And the random.php
<?php
$imagesDir = 'img/random-dice-6-sides/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)];
echo $randomImage;
?>
You can see the whole process on https://randomster.com/random-dice-6-sides.php
The orange button is the php call, and the white is the Javascript call.
Thanks for your help! Greetings