Forum Moderators: open

Message Too Old, No Replies

Loading image.src, same filename, cache issues

         

Nutter

9:30 pm on Feb 21, 2009 (gmt 0)

10+ Year Member



I'm working on a little piece of javascript that refreshes an image after upload, but am having issues with the browser cache. The PHP script that handles the upload overwrites the current image with the newly uploaded image. I'd like to be able to refresh the image in the browser without refreshing the entire page, but since it's saving the file as the same name it's pulling the copy from the cache. Is there a way to tell the browser to not pull the image from cache using JS?

Edit...

Found a work around. I appended ?some-random-string to the end and it works perfectly.

[edited by: Nutter at 9:38 pm (utc) on Feb. 21, 2009]

rocknbil

4:13 pm on Feb 22, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Sure is. Generate a unique ID from your PHP script (or Javascript) and do this:

<img src="same-image-name.jpg?12345678">

For Javascript, An easy way is to use the Date() and getTime() functions, often used for the id attribute of new windows (to insure a new window always opens instead of the same window with new content.) Even if you have multiple images on the same page, it's unlikely the current time will be the same as the last time the page was refreshed:

var day = new Date();
var id= day.getTime();
target_img.src= target_img.src+'?'+id;

(Might have my syntax wrong, but that's the idea)

Nutter

6:49 pm on Feb 22, 2009 (gmt 0)

10+ Year Member



That's almost exactly what I wound up doing. The JavaScript that refreshes the image is called inside a hidden iframe and output using PHP so I just appended ? and a uniqid() to the end of the src. Worked like a champ.

I like the time idea and am going to put that in my bag of tricks for when I need a totally JS solution.