Using Javascript you can reload an image without reloading the page. This is extremely useful for reloading a captcha image if the user is unable to read the characters shown in it. Reloading an image using Javascript is just a simple matter of reassigning the same image location to the image src attribute. But the problem is the browser doesn’t call the image from the web server, since the name is same the browser just fetches the same image from the cache (Temporary Internet Files). So to overcome this we must add something with the image src attribute in such a way that it doesn’t affect the image location. The best way to do it is to add it like a query string to the image.But what do we add ? We can generate random numbers or alphanumeric characters and append as a query string. But if incase the same random string is generated when a user presses the reload button the image will not be reloaded from the server. So the best way to make sure the value is unique each and every time is to use the function getTime() this function returns milliseconds since 1970/01/01 so this value will be definitely unique each time the user clicks the reload button unless clicking is done twice in a millisecond !!! Place the following code inside either the <head> tag or <body> tag. But before that set the id attribute of that image to imageid or if you modify it do that same to the inside getElementById()
<script type="text/javascript"> function reloadImg() { var d=new Date(); document.getElementById("imageid").src="captcha_image.php?a="+d.getTime(); } </script>
The function must be called through a link or button. For calling it through a link
<a href="javascript:reloadImg()">Reload Image</a>
For calling the same through a button
<input type="button" value="Reload Image" onclick="reloadImg()" />
Try a live demo with a captcha image.
Andy says
Works perfectly. Thanks!
Deepak says
help ful..