Reputation: 1521
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.
Upvotes: 10
Views: 34066
Reputation: 466
Adding a time span to the end of the image URL worked for me.
var imagePath = "http://localhost/dynamicimage.ashx";
$("#imgImage").attr("img", imagePath + &ts" + (new Date()),toString() );
Upvotes: 1
Reputation: 91677
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);
});
Upvotes: 13
Reputation: 4373
It seems there is something wrong with your Perl script. Trying to access the image by the URL should return an image anyway. It should return binary data and not a script. You should also set the Content-type header of the response to image/gif. Verify if it indeed returns binary data before trying to fix your JavaScript code.
Upvotes: 4
Reputation: 7653
every X seconds send Ajax to server. if link of image from response == previous, no update, if link new: $('img.class').attr('src','link');
Upvotes: 0
Reputation: 2237
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);
Upvotes: 10
Reputation: 31662
just use javascript to update the src property of the img.
HTML:
<img src="..." id="myImage" />
JS:
document.getElementById("myImage").src = "http://....";
If you want it on a timer, do something like this:
setInterval(function() { ... }, 4000);
If you have an issue with caching, add a random query string to the end of the url: "?rnd=randomNumberHere"
Upvotes: 4