wil
wil

Reputation: 2137

How do I refresh a remote picture?

I have a picture in a DIV on site abc.com which is hosted elsewhere, for example <IMG SRC="http://xyz.com/image.jpg">.

It loads fine, but, I need to update this every few seconds.

The majority of items to upload are local, but the following code will not work for remote pictures:

$('#rightpic').load('http://xyz.com/image.jpg', null);

By trying this, I am getting an error : ...is not allowed by Access-Control-Allow-Origin.

Can anyone recommend a better way of doing this?

Upvotes: 0

Views: 95

Answers (2)

Joseph
Joseph

Reputation: 119847

.load uses an AJAX request, thus the same origin policy applies - which restricts cross-domain requests. Besides, it's not the best way to load images anyway. Also, setting the same url as src will often load images from the cache.

Instead, you should add a random query string value every request, like a timestamp, to "bust the cache"

var img = document.getElementById('rightpic');

//update every 10 seconds using time from epoch as random value
setInterval(function(){
    var randomValue = new Date().getTime();
    img.src = "http://example.com/image.jpg?t="+randomvalue;
},10000); 

Upvotes: 1

Bryan
Bryan

Reputation: 6752

Try this out, you want to actually change the src, not use the .load() function.

$('#rightpic').get(0).src = 'http://xyz.com/image.jpg';

Upvotes: 3

Related Questions