0

I'm trying to work through a question previously asked on stckoverflow - "Using AJAX / jQuery to refresh an image"

Using AJAX / jQuery to refresh an image

The URL from image_feed.php is supposed to change everytime. However, I can't figure out what the code for image_feed.php should be (even an example). Can anyone help?

FYI, my index.php is:

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
    var $img = $('#image1');
    setInterval(function() {
        $.get('image_feed.php?CAMERA_URI=<?=$camera_uri;?>', function(data) {
            var $loader = $(document.createElement('img'));
            $loader.one('load', function() {
                $img.attr('src', $loader.attr('src'));
            });
            $loader.attr('src', data);
            if($loader.complete) {
                $loader.trigger('load');
            }
        });
    }, 5000);
});
</script>
</head>
<body>

<div id="image1">
</div>
</body>
Community
  • 1
  • 1

3 Answers3

1

The image_feed.php should just return the image's src as the response.

<?php
// produce the src with your logic.
$src = "https://www.gravatar.com/avatar/daa6ae7c970d99c6c2b3a9d8895aaa1e?s=32&d=identicon&r=PG";
echo $src;
xdazz
  • 158,678
  • 38
  • 247
  • 274
0

Try this:

<!DOCTYPE html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <script>
            $(document).ready(function() {
                var $img = $('#image1');
                setInterval(function() {
                    $img.attr('src', 'image_feed.php?CAMERA_URI=<?=$camera_uri;?>');
                }, 5000);
            });
        </script>   
    </head>
    <body>
        <img id="image1" src="image_feed.php?CAMERA_URI=<?=$camera_uri;?>">
    </body>
</html>
Stanislav Terletskyi
  • 2,072
  • 20
  • 17
0

Try this

$(function() {
  var $img = $('#image1');
  var loading = false;
  setInterval(function() {
    if ( loading === true ) {
      return;
    }
    loading = true;
    var image = new Image;
    image.src = <?php echo json_encode( "image_feed.php?CAMERA_URI=".urlencode( $camera_uri ) ); ?>;
    image.onload  = function() {
      loading = false;
      $img.attr("src",this.src);
    };
    image.onerror = function() {
      loading = false;
      // do something here
    };
  }, 5000);
});
bystwn22
  • 1,776
  • 1
  • 10
  • 9