0

I'm trying to use setInterval() to reload an image from a given path. I have some similar code to reload a log file which is working fine:

var auto_refresh = setInterval(
    function auto_refresh_log()
    {
        $('#log_output').load('refresh_log.php').fadeIn("slow");
    }, 1000);

refresh_log.php:

<?php  $file = "/var/www/html/mainLOG";     
    $contents =  file($file);   
    $string = implode( $contents);  
    echo $string; ?>

Now, I want to do something similar only with 2 changes:

  • Instead of using a fixed path like in refresh_log.php, I want to pass the path from the JS function to the PHP file. How can I do that?
  • Instead of returning a string, I want to return an image, which is then used in my html document. How can I do that?

To be exact on what I want to do: I have an index.php on which a user can select a file path. After setting some further parameters, some calculations start in the background. The results are saved as TIFF-files which cannot be read by the browser. So I want to use a PHP script with imagemagick to convert them (which is working fine) and pass them back to the JS. Then, the image should be displayed on my HTML <img id="image_id" ... > and refreshed every couple of seconds just like the log file.

Thanks!

Dominic
  • 452
  • 4
  • 20

2 Answers2

0

One way would be to change the src attribute of the img element.

The browser will download the resource when you change the the src of the img element. Use the jQuery attr to do this. You should append a timestamp parameter so the browser does not obtain a cached instance from the local browser cache.

function loadImg(src) {
    // append a parameter of "_" to the url
    $("#myimg").attr("src", src + "?_=" + Date.now());
}
setInterval(loadImg("path/to/img"), 1000);

On your PHP side you would need a script that servers the image up in your converted format from where ever you are storing it. An example of how to do that is here.

Community
  • 1
  • 1
George Lee
  • 826
  • 6
  • 11
0

I've managed to come up with a solution using $.post instead of $.load. The function is called via:

setInterval(
    function auto_refresh_img()
    {
        var img_path = document.getElementById("image_path").value;         
        $.post('refresh_img.php', 
                {path: img_path}, 
                function(data) {
                     $('#my_div').html(data);}
              );
    }, 1000);

with refresh_img.php looking like this:

<?php $imagepath = $_REQUEST['path'];

if (file_exists($imagepath))  {

    $img = new imagick($imagepath."[0]");
    $img->setImageFormat('jpg');
    $thumbnails0 = $img->getImageBlob();

    echo "<img src='data:image/jpg;base64,".base64_encode($thumbnails0)."'  id='reco_background' style='display:none'   />";
}
else {
    echo "Image does not exist.";
    };
?>

The returned <img ... > may then be used for any purpose.

Dominic
  • 452
  • 4
  • 20