views:

172

answers:

2

Hi Guys,

I am trying to refresh an image on the page but it is not happening. I have a page with images and I need to update those images as required. To update an image I upload the image on a lightbox and then close the lightbox. The image on the page should update itself. Now, I tried $('#imageid').attr('src', newimage). I want to make a special mention here that the name of both the old and new images are same. And I feel this is the problem. If I hard code any other image it does appear as soon as the lightbox closes. But, when I try to refresh the image by putting the same image name for the 'src' attribute then nothing happens.

Can someone help me out how I can fix this issue and show the updated image.

Thanks.

Edit: Could it be the cache?

+1  A: 

If src is "foo.png" and you set src to "foo.png", I think the assignment will probably get optimized out by the browser as a no-op. Have you tried setting src to "", and then setting it to the name? That should register as a change.

T.J. Crowder
Yes, I tried this already but this didn;t work. I set the src to blank and then set it back to the image. It was setting the src to blank but then when it set the src back to image it would load the old image.
Blueboye
@Blueboye: Ah, well, it was worth a shot...
T.J. Crowder
+3  A: 

There's probably a better solution, but you could just throw on a parameter to force a new image load.

i.e.: Set the src to newImage+"?"+(new Date()).getTime()

Stefan Kendall
Good point, if just clearing `src` first doesn't work.
T.J. Crowder
Yes this is what I have done as a work around but I am not sure if this is just a work around or the only solution. I would want something more cleaner and logical, unless this is the only way to make the browser refresh the image.
Blueboye
You might want to check into the jQuery source. It might make optimizations when the values of the attributes are the same. That said, I'm not sure what the browser behavior SHOULD be if you "re-set" to the same image. If I were a browser developer, that would be ambiguous to me. You could always make a function to abstract away the "new Date()" bit.
Stefan Kendall
jQuery doesn't do this optimisation, but a browser might. Anyhow, browser caching will certainly get in the way unless you've set nocache headers on the image itself. It is normal to use a cachebreaker such as the timestamp (+1) or a random number.
bobince
Oh ok. Thanks a lot guys. This forum rocks. The original jQuery.org forum sucks.
Blueboye