PHP/MYSQL Change an image when a radio button is selected without refreshing the page.

ct8270 used Ask the Experts™
I have 3 radio buttons that have an image associated with it stored in a mysql database. I am trying to change a main picture on the same page dynamically when one of the radio buttons is selected. I need to do this without refreshing the page if possible.

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2007
It's not realy a php-question, more javascript like this in HTML:

<img id="displayimg" src="1stimg.gif">

<input type="radio" name="x" value="1" onclick="document.getElementById('displayimg').src='2ndimg.gif'">
<input type="radio" name="x" value="2" onclick="document.getElementById('displayimg').src='3ndimg.gif'">
To expand upon hernst42's answer, if the images are loaded in the database, you have two options.

1) During page load, use PHP to query the database for the image file name.  Dynamically create javascript function using the image file name:

<script type="text/javascript">
  function showImageOne() {
     document.getElementById('imageId').src = "<?php grabImageOneName(); ?>";

2) Use ajax to grab the other images filenames.  If you're new to php/ajax, method 1 is probably the easiest.

I've done something simular to this before. The way I did it was to use a PHP page that is passed the ID of the image I wanted, which is then pulled from the database and the image is then outputted to the page and the headers changed to force a download of the image.

So in a file named "get_image.php" for example you put the following code:

      /* get image id */
      $id = trim($_GET['id']);
      /* get image data */
      $query = "SELECT data FROM table WHERE id='$id' LIMIT 1";
      $result = mysql_query($query);
            $rst = mysql_fetch_assoc($result);
            /* get file */
            header("Content-Type: application/octet-stream");
            header("Content-Disposition: attachment; filename=image.jpg");
            header("Content-Length: " . strlen($rst['data']));

Then on your html page you have a script that is called on the click of the radio buttons that is passed the ID of the image you want, that then requests the image from the above PHP page.

<script type="text/javascript">
  function GetImage(ID) {
     document.getElementById('image1').src = "get_image.php?id=" + ID;

<img id="image1" src="javascript:GetImage('1');">

<input type="radio" name="rad1" value="1" onclick="javascript:GetImage('1');">
<input type="radio" name="rad2" value="1" onclick="javascript:GetImage('2');">
<input type="radio" name="rad3" value="1" onclick="javascript:GetImage('3');">

I think that should work.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial