1

Im a PHP noob, trying to make a random picture generator with a random image button. When I click the button I want a new image to come up. How ever this only works once. What should I change to make it work several times?

Code:

<html> 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<script> 

function changeImage()
{
var img = document.getElementById("image");
img.src="/cats/<?php echo rand (1,92);?>.jpg";
return false;
}

</script>

</head>

<body>

<img id="image" src="/cats/<?php echo rand (1,92);?>.jpg" width="500" height="500" />
<br><br><br>
<button id="clickme" onclick="changeImage();">Click to change image!</button>
</body>

Thanks in advance!

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141

3 Answers3

1

Adjust your javascript code:

function changeImage()
{
    var random = Math.round(1+Math.random()*92); // random between 1 and 92
    var img = document.getElementById("image");
    img.src = "/cats/" + random + ".jpg";
    return false;
}
Fracsi
  • 2,274
  • 15
  • 24
1

PHP is a server-side language. This is different than javascript, which is client-side. PHP code is executed when the user first accesses the page, and is used to generate page content. The browser sees this content, but it never sees the actual php code. Javascript, on the other hand, is sent to the browser, and the browser uses it dynamically while the user has the page open. For example, the following line:

<img id="image" src="/cats/<?php echo rand (1,92);?>.jpg" width="500" height="500" />

will be transmitted to the browser as, for example:

<img id="image" src="/cats/37.jpg" width="500" height="500" />

That then becomes all the browser sees. Until the user refreshes the page, every time you run your javascript function, the image 37.jpg will be displayed.

IanPudney
  • 5,941
  • 1
  • 24
  • 39
  • Great answer, +1. Except you only explained why it doesn't work but don't provide a solution - that all he needs to do is generate the random integer inside of `changeImage()` with JS instead of PHP. It would be nice to edit your answer to fix his problem (by updating the PHP rand() with its Javascript equivalent) too seeing as it is a very simple change - see Fracsi's answer below. – Ennui Jun 26 '13 at 20:12
0

the PHP code runs only once when the page is loaded.

use a javascript random number generator

Dan
  • 3,755
  • 4
  • 27
  • 38