depecheSoul
depecheSoul

Reputation: 966

Change image every second using PHP and JavaScript

I have a small script written in JavaScript that is used to change picture every second. The problem is that image is not being changed.

The image file that shuld be displayed is overwritten every second, with the new data.

Displaying the first image on the webpage works fine, but getting all of the subsequent images does not work, always the same picture is displayed.

JQuery code contains time extension to force the browser to reload new image every time and to not take it from the cache.

You can see the JQuery code for image loading.

<script type="text/javascript">
    var auto_refresh = setInterval(function (){
            $('#image').load('camera_stream_worker.php?time=' + Date.now());}
    , 1000);
</script>

This is the return of the worker file:

<?php
  echo '<img src="/RAMdisk/image.jpg" />';
?>

On the picture ou can see the network traffic.

network analysis using firefox

So my question is: how can I display different picture every second?

thanks

Upvotes: 0

Views: 1593

Answers (2)

Henry Zou
Henry Zou

Reputation: 1917

ajax method:

may need to specify different content-type in the header.

$.ajax({
  method: 'get',
  url: 'camera_stream_worker.php?time=' + Date.now()) 
}).success(function(data) {
  $('#image').html(data);
})

Could be that the image names are all the same, therefore it doesn't get new ones. try to add a timestamp to your images:

<?php
  echo '<img src="/RAMdisk/image.jpg?<TIMESTAMPHERE>" />';
?>

this answer assumes the result were image srcs.

have you tried changing the src instead of load?

<script type="text/javascript">
    var auto_refresh = setInterval(function (){
            $('#image').attr('src', 'camera_stream_worker.php?time=' + Date.now());}
    , 1000);
</script>

Upvotes: 2

epascarello
epascarello

Reputation: 207557

The issue here appears to be the fact you are returning an html document instead of just the image that is changing. The HTML has a hardcoded image.jpg in the source and since that does not change it is being pulled from the cache.

What you would need to do is change that image source to fetch the latest image and not update the entire html snipplet around it.

Other option is to make the php append the timestamp to the html.

Upvotes: 0

Related Questions