user198729
user198729

Reputation: 63656

How to refresh the src of <img /> with jQuery?

<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.

Upvotes: 29

Views: 59152

Answers (4)

SeanDowney
SeanDowney

Reputation: 17754

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;
    });
});

Upvotes: 6

claws
claws

Reputation: 54100

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

Upvotes: 0

K Prime
K Prime

Reputation: 5849

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());
});

Upvotes: 59

Kobi
Kobi

Reputation: 138037

Add a timestamp or a random number:

var timestamp = new Date().getTime();
$(this).attr('src',$(this).attr('src') + '?' +timestamp );

Upvotes: 9

Related Questions