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.
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 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.
Just right on image and select "reload this image" or right click on page and click "reload all images" in Tab or Window.
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);
});
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With