29
<img src="test.php" />

where test.php generates an image with a random number.

Itried :

$('#verifyimage').click(function() {
        $(this).attr('src',$(this).attr('src'));
    });

But it doesn't work.

user198729
  • 61,774
  • 108
  • 250
  • 348

4 Answers4

59

You can force a refresh by appending a random string at the end, thus changing the URL:

$('#verifyimage').click(function() {
    $(this).attr('src', $(this).attr('src')+'?'+Math.random());
});
K Prime
  • 5,809
  • 1
  • 25
  • 19
  • 2
    Eww. No, don't. Set appropriate caching response headers on the server instead. – Nicolás Jan 04 '10 at 23:43
  • 2
    `Cache-control`, `Expires`, et al. only work once a HTTP request is received - the above is simply to force the client to make that request. In the absence of a `Image.reload` (AFAIK), this was the simplest method to make a new request – K Prime Jan 06 '10 at 03:36
  • 6
    would suggest substring on the src attribute to a "?" so that after the first time, it doesn't keep appending more querystring data... – Tracker1 Jan 08 '10 at 10:30
  • This is the same strategy as in jeerose's reply in this thread: http://stackoverflow.com/questions/2104949/how-to-reload-refresh-an-elementimage-in-jquery – Vanja Jun 14 '13 at 11:05
  • @KPrime This is great!! I struggled many hours to make it work. Thanks!! – Dilip Feb 01 '18 at 19:37
9

Add a timestamp or a random number:

var timestamp = new Date().getTime();
$(this).attr('src',$(this).attr('src') + '?' +timestamp );
Kobi
  • 135,331
  • 41
  • 252
  • 292
  • 2
    The timestamp is a better solution! You can't rely on random not to be be the same sometimes. – jerwood Sep 07 '11 at 07:14
  • tried this but having problem in chrome. Image src gets appended with the timestamp but thumbnail is not getting refreshed. Can you suggest me anything on this? – Rohan Patil May 24 '12 at 09:58
  • @RohanPatil - There is an obvious issue here - you want to **add or update** a query **parameter** - this code is just a partial solution - it assumes there are no query parameters to begin with (In addition, I suspect it only works once). – Kobi May 24 '12 at 10:47
6

Taking KPrimes great answer and adding in trackers suggestion, this is what I came up with:

jQuery(function($) {
    // we have both a image and a refresh image, used for captcha
    $('#refresh,#captcha_img').click(function() {
       src = $('#captcha_img').attr('src');
   // check for existing ? and remove if found
       queryPos = src.indexOf('?');
       if(queryPos != -1) {
          src = src.substring(0, queryPos);
       }    
       $('#captcha_img').attr('src', src + '?' + Math.random());
       return false;
    });
});
SeanDowney
  • 17,368
  • 20
  • 81
  • 90
0

In test.php set the headers of Content-Type: to image/jpeg

claws
  • 52,236
  • 58
  • 146
  • 195