I have the following function. When I click the first time, it returns a random number, but all subsequent clicks always return the same number. How come it doesn’t refresh?
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btn-get-random-image').click(function () {
$('#my-img').attr('src', '<?php echo $pics[array_rand($pics, 1)]; ?>');
});
});
</script>
As others have said, you are using PHP, which is executed once on the server and sent as raw output, so the image will not change. Try this!
Edit: modified code to make it suck less.
This uses PHP’s JSON encoder to dump your array to the javascript, then your function randomly selects an image from that array to display. The
do/whileloop might not be necessary, my testing shows a pretty good near-uniform distribution over thousands of iterations, but there it is nonetheless.