Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic image refresh

How would I go about updating an image that gets updated on a server every couple of seconds with out the user having to hit the refresh button, my first guess was ajax but I haven't really worked with it before. Could someone point me in the right direction?

EDIT: Forgot to mention that the image is a .gif generated by a perl script - trying to get it from url returns the script itself.

like image 655
Gunslinger Avatar asked Jun 28 '11 16:06

Gunslinger


People also ask

How do I refresh IMG tags?

To refresh the image in JavaScript, we can simply select the img element and modify its src attribute to be that of the target image, along with the timestamp parameter to ensure it does not access it from the cache.

What are dynamic images?

What is a dynamic picture? Dynamic means that the picture changes when you change some input. A dynamic picture looks different in different situations. Here are examples of different types of pictures: This is a static image.

How do I reload photos?

Just right on image and select "reload this image" or right click on page and click "reload all images" in Tab or Window.


2 Answers

No AJAX is necessary, just update the image's src property. But, since it has the same url, you have to give the browser a unique address to ensure you don't just load the old image from the browser's cache. You can guarantee a unique image by getting the current date's serial number via new Date().valueOf() and appending that to the url as a querystring.

$("#dynamicImage").prop("src", "dynamicImage.jpg?" + new Date().valueOf());

You can also use new Date().getTime() to get the serial number, or just coerce the date to a number: +new Date()

To do it on a timer use setInterval(). This would be the complete code that you could just drop inside a script tag in your page's <head>:

$(function() {
   var intervalMS = 5000; // 5 seconds
   setInterval(function() {
      $("#dynamicImage").prop("src", "dynamicImage.jpg?" + +new Date());
   }, intervalMS);
});
like image 109
gilly3 Avatar answered Oct 11 '22 01:10

gilly3


Do something like

document.getElementById('yourimage').src = "url/of/image.jpg?random="+new Date().getTime();

This changes the src attribute of your image tag (with id "yourimage") and adds a random query string to it, forcing the browser to reload the image each time you change it.

To reload the image every 5 seconds, do something like:

window.setInterval(function()
{
    document.getElementById('yourimage').src = "url/of/image.jpg?random="+new Date().getTime();
}, 5000);
like image 32
Steffen Müller Avatar answered Oct 11 '22 01:10

Steffen Müller