Reload an image using Javascript/Ajax

Hi all,

I’m completely new to javascript/jquery/ajax/etc (though have loads of experience coding in other languages) and I’m hoping to reload an Image in response to a user interaction with a page (a jquery slider UI element) on my site (in signature). (For complete accuracy a server side program is called in response to the slider and then the image is reloaded).

So my questions are: will this be relatively straightforward? And secondly do you know of any links that might be useful for me in getting started with this?

Many thanks!

I guess my question is probably a little too vague - I’ll do a spot more investigation myself and then I’ll come back with more focused questions

If you change the src of an image, it’ll cause that image to load.

If you want to load the same image again, you can append something random to the end, after a question mark.

Ex., I have an image called “image.png”. I want to force it to reload, so I just add something random to the end, like a random number, so it becomes:
“image.png?1542”. The same file will load, but the browser thinks it’s different, so it causes it to load again.

Hope that helps.

Thank you for the tip… I wanted to have an image refresh whenever a user came to the page. It helped me come up with the idea to use PHP to generate a random number, thus forcing the browser to refresh.

<img src="this-week.png?<?php echo rand(5, 9); ?>" />

Thanks so much for the info! I now have the image reload working fine, never thought it would be so straight forward. The next thing I need to do is to call a php file via ajax. Is it straight forward to get the image reload to wait until the ajax call has finished?

Many thanks again!

Yes but you’d need to do it using JavaScript from within the function that runs when the Ajax call returns rather than doing it from PHP.

thanks - that makes sense

For the most part the image reload is working perfectly - though for larger images, there is a noticeable delay between clicking the link/button and the image reloading - would it possible to show a twirling animation before the file is actually ready for reload?

Yeah, you’d want to use a preloader.

Here is an article which describes one approach to it: Preloading and the JavaScript Image() object | TechRepublic

Great suggestion - I’m off to implement this. I think I still need to figure out how to display a spinning gif when loading content. Maybe for another day and a separate thread. thanks everyone for the help!

Basically all you do is hook in an event for when the image is done loading.

Then, when you go to change it, change it to the spinning gif.
Then, once it’s done loading, change the spinning gif to the image you just loaded.