0

I have the below code that I was helped with on a previous question (http://stackoverflow.com/questions/10920514/using-ajax-jquery-to-refresh-an-image)

The way this worked was that image_feed.php returned a url to an image. The snippet below downloaded this image, and then swapped it out with an existing image on the page.

I have now changed the way my application works, and the URL of the image will not change as before so I can bypass the image_feed.php script.

So I have a image, image.php?id=11, and I need to download this image, wait for it to finish loading and then swap it with the #camera_image_changer image.

I am struggling with two things. One is remembering how the script actually works again so as I can give it the image URL directly and secondly preventing it caching the image.

Any help would be greatly appreciated.

Thanks

// image feed
var $img = $('#camera_image_changer'); 

 setInterval(function() {

    $.get('../helpers/image_feed.php?camera_id=11', function(data) {
    var $loader = $(document.createElement('img'));

     $loader.load(function() {
        $img.attr('src', $loader.attr('src'));
     });

     $loader.attr('src', data);

    });

}, 5000);

Update: I may have answered my own question. I have the below code and it is working, is this a OK way to do it?

// image feed
var $img = $('#camera_image_changer'); 

setInterval(function() {

        var $loader = $(document.createElement('img'));

        $loader.load(function() {
            $img.attr('src', $loader.attr('src'));
        });

        $loader.attr('src', '../helpers/image.php?<?=$resource;?>=<?=$resource_id;?>');

}, 5000);
dopey
  • 496
  • 1
  • 6
  • 19

1 Answers1

1

You can remove the get call and use only the code inside of it, assigning the data variable the path to the image:

var $img = $('#camera_image_changer');   

// this delay the code execution in milliseconds
setInterval(function() { 
    var data = "path/to/image.jpg";

    // Creates an image object and pass it to jQuery return a jQuery object
    var $loader = $(document.createElement('img')); 

    // Create a callback that fires when the image finishes loading
     $loader.load(function() { 
        // assign the source of the loaded image to the target image
        $img.attr('src', $loader.attr('src')); 
     }); 

     // assign the image to load
     $loader.attr('src', data);
 }, 5000); // 5 seconds (5000 ms)

In your previous code, the get method calls the page and returns the contents as the data variable.

Ricardo Souza
  • 16,030
  • 6
  • 37
  • 69