How to reload image using javascript

How can I reload this image to get a new one from the server using javascript without reloading the page?

<img src="?option=com_fcse&task=getimage&width=100&height=40&characters=5&r=<?php echo mt_rand(0, 10000000); ?>" /> 

thanks

+4
source share
3 answers

This should do it:

 thatImgObj.src = thatImgObj.src.replace(/&r=\d+/, "&r="+ ~~(Math.random()*1e7)); 

(Of course, with a chance of 1e-7 getting the same cache key again - timestamping might be the best option)

+2
source

Well, the easiest way is to change the src attribute in Javascript. So: YouImageElement.src += "&rand2"+Math.random();

Changing the src attribute will reload the image, and since it has another random number set on the client side, it cannot be cached.

+1
source

Your code

Added id="img1"

 <img id="img1" src="?option=com_fcse&task=getimage&width=100&height=40&characters=5&r=<?php echo mt_rand(0, 10000000); ?>" /> 

JS Code:

 var newImage = new Image(); newImage.src = document.getElementById("img1").src + "&_=" + new Date().getTime(); 

Added cache breakout at end of url

+1
source

All Articles