Jump to content

refresh image each 10 secondes


raldje

Recommended Posts

Hi,

first sorry for my english, i'm french

i got a table in my database to announced events with this fields: id, event_date, announce, image.

I want to make a header with images changing each 10 secondes, but i don't want to refresh all the page.

 

This is what i use actually:

$rst = $bdd->query('SELECT image from matable order by Rand() LIMIT 0, 1');
while($donnees = $rst->fetch())
{
$image = nl2br($donnees['image']);
if (empty($image)) {
echo '<img src="imagedefaut.jpg" />';
}
else {
echo '<img src="image/'.$donnees['image'].'" alt="image"/>';
}         
}
$rst->closeCursor();

I know i have to use some javascript with setInterval but i don't know how to do.

Can i have some help, please.

Link to comment
Share on other sites

here is an eg :

<img src="./01.png" id='img1'/>
<img src="./02.png" id='img2'/>
<script>

var x=1;
        var myVar = setInterval(myTimer, 1000);

function myTimer() {
   if(x%2==0){
	document.getElementById("img1").style.display = "none";
	document.getElementById("img2").style.display = "block";
        x=1;
		}
	else{
	     document.getElementById("img2").style.display = "none";
	document.getElementById("img1").style.display = "block";
	x=2;
	}	
}
</script>

all you have to do is get some images and set the SRC path to the right location .

Link to comment
Share on other sites

$rst = $bdd->query('SELECT image from matable order by Rand() LIMIT 0, 1');
while($donnees = $rst->fetch())
{
$image = nl2br($donnees['image']);
echo '<img src="defaultimg.jpg" alt="image_by_default" id="img1"/>';
echo '<img src="image/'.$donnees['image'].'" alt="image" id="img2"/>';
}
$rst->closeCursor();

<script>

var x=1;
        var myVar = setInterval(myTimer, 1000);

function myTimer() {
   if(x%2==0){
	document.getElementById("img1").style.display = "none";
	document.getElementById("img2").style.display = "block";
        x=1;
		}
	else{
	     document.getElementById("img2").style.display = "none";
	document.getElementById("img1").style.display = "block";
	x=2;
	}	
}
</script>

When i load the page i see 2 images and after 1 second, it's working.

But it's only switch beetween default_img and first event image, i got several events with image in my table.

 

 

You can use ajax to call the same php code

I realy don't know how to do this.

Edited by raldje
Link to comment
Share on other sites

$rst = $bdd->query('SELECT image from matable order by Rand() LIMIT 0, 1');
while($donnees = $rst->fetch())
{
$image = nl2br($donnees['image']);
echo '<img src="defaultimg.jpg" alt="image_by_default" id="img1"/>';
echo '<img src="image/'.$donnees['image'].'" alt="image" id="img2"/>';
}
$rst->closeCursor();

<script>

var x=1;
        var myVar = setInterval(myTimer, 1000);

function myTimer() {
   if(x%2==0){
	document.getElementById("img1").style.display = "none";
	document.getElementById("img2").style.display = "block";
        x=1;
		}
	else{
	     document.getElementById("img2").style.display = "none";
	document.getElementById("img1").style.display = "block";
	x=2;
	}	
}
</script>

When i load the page i see 2 images and after 1 second, it's working.

But it's only switch beetween default_img and first event image, i got several events with image in my table.

 

 

You can use ajax to call the same php code

I realy don't know how to do this.

Link to comment
Share on other sites

Place all required code to produce random image using html img tag in a php file.

 

Look at this http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first you are basically replacing the paragraphs from the text file with your random img tag produced with your php file.

 

But instead running ajax code on button click you run it using setInterval.

Link to comment
Share on other sites

I'l try to explain with more precision.

In my table i have several entries of event, some with image, some without

I also have an image by default .

I try to make a header with all the present images in my table switching every 10 seconds, or my image by default if no event or only events without image.

Edited by raldje
Link to comment
Share on other sites

this code is help full to you check once

 

Initially you can save all images in one variable then,

 

$(document).ready(function()
{
window.setInterval(function(){
countdown();
}, 1000);// every one second
});

 

function countdown() {

// build your logic to get random images from that variable

}

Link to comment
Share on other sites

create php file that holds random image php script from database

 

random_image.php (note i created a quick connection to database images which is probably not setup as yours).

<?php

$db_host = 'host';
$db_user = 'user';
$db_pwd = 'password';

$database = 'whatever';


$bdd = new mysqli($db_host, $db_user, $db_pwd, $database);
// Check connection
if ($bdd->connect_error) {
    die("Connection failed: " . $bdd->connect_error);
}
$rst = $bdd->query('SELECT image from matable order by Rand() LIMIT 0, 1');

   while ($donnees = $rst->fetch()) {
    $image = nl2br($donnees['image']);
    if (empty($image)) {
        echo '<img src="imagedefaut.jpg" />';
    } else {
      
        echo '<img src="image/'.$donnees['image'].'" alt="image"/>';
    }
}
$rst->closeCursor();

Now we include this file in the page that uses this random image script to produce your current setup, this will always produce a random image on loading of page whether js disabled or not.

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" id="viewport" content="target-densitydpi=high-dpi,initial-scale=1.0,user-scalable=no" />
        <title>Ajax random image</title>
        <script type="text/javascript">

            window.onload = function() {

                window.setInterval(function() {
                    show_random_Image();
                }, 10000);
            }

            function show_random_Image() {
                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function() {
                    if (xhttp.readyState == 4 && xhttp.status == 200) {
                        document.getElementById("random_image_wrap").innerHTML = xhttp.responseText;
                    }
                };
                xhttp.open("GET", "random_image.php", true); //note path to script may need amending
                xhttp.send();
            }
        </script>


        <style type="text/css">

        </style>
    </head>
    <body>
        <div id="random_image_wrap">
            <?php
            include ('/random_image.php'); // include random image script to you produce current random image effect note path to script may need amending
            ?>
        </div>

    </body>
</html>

Now the JavaScript ajax script will run at 10 sec interval on loading of page a connection to random_image.php it will retrieve the content produced by that php script and insert it into the element with id reference of 'random_image_wrap' overwriting the current image that is in there, without reloading of the page.

Edited by dsonesuk
Link to comment
Share on other sites

With php you could create a JavaScript array of all your images, then use JavaScript to select a random number between 0 and total number of images in array minus one (array index start at 0) then use this random number as a index ref of the image to use.

Link to comment
Share on other sites

<?php
$stmt = $bdd->query('SELECT image FROM matable');
$donnees = $stmt->fetchAll();
var_dump($donnees);
$images = $donnees['image'];
echo '<img src="image/'.$images.'" id="my-image" />';
?>
  
<script type="text/javascript">
    var imgs = new Array(
        <?php
        for ($i = 0; $i < count($images); $i++) {
            echo '"'. htmlspecialchars($images[$i]) .'"';
            if ($i < count($images) -1) {
                echo ',';
            }
        }
        ?>
    );
    var position = 0;
    var taille = imgs.length;
    var image = document.getElementById('my-image');
    changeImage = function() {
        position = (position+1 >= taille) ? 0 : position+1;
        image.src = imgs[position];
        setTimeout(changeImage, 1000);
    }
    changeImage();
</script>

I think it's something like that but it don't work.

Link to comment
Share on other sites

Unless the image array img src contains the path also as in 'image/' it will replace img src with 'myimage.jpg' instead of 'image/myimage.jpg;

 

and shouldn't this

 

$donnees = $stmt->fetchAll();

 

be

 

$donnees = $stmt->fetch_all();

 

 

Also with the way you are accessing the img src it should be more like $images[$i][0] ?

Link to comment
Share on other sites

you can also use the image directory to lest images from

<div id="mypic"></div>
	 <script>
	   var myVar = setInterval(myTimer, 1000);
	  var images = [];
      <?php 
	  
	  // set $dir to your image directory
	  $dir = "./res/images/";

// Open a directory, and read its contents
if (is_dir($dir)){
  if ($dh = opendir($dir)){
    while (($file = readdir($dh)) !== false){
	 if (!is_dir($file))
	 {
	  ?>
	  //fill up the JS array with php values
	  images.push("<?php echo  $file; ?>");
	  
	 
	   <?php
	   }    
	}
    closedir($dh);
  }
}

  
?>

function myTimer() {
   var tt=Math.floor((Math.random() * images.length) + 1) - 1;
	document.getElementById("mypic").innerHTML  = "<img src='./res/images/" + images[tt] + "'>";
	
	
}
 
	 </script>
	 

Link to comment
Share on other sites

  • 1 year later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...