Evgeny Tryastsin
Evgeny Tryastsin

Reputation: 733

captcha dynamic renew with php and jquery

Would appreciate any piece of advice on this. Need to dynamically renew the captcha image generated by php-script, when the "captcha_refresh" is clicked. Below is the way I tried to achieve it. Unfortunately this approach works fine only with Google Chrome, and other browsers seem not to understand this.

HTML

<img class="captcha_image" src="http://localhost/shop/create_image.php"/>
<a class="captcha_refresh" href="http://localhost/shop/create_image.php">
    <img src="http://localhost/shop/images/captcha_refresh.png"/>
</a>

JQuery

$('a.captcha_refresh').live('click', function (event) {
    event.preventDefault();
    $('img.captcha_image').attr('src', $(this).attr('href'));
});

The PHP prints the image:

header("Content-Type: image/jpeg");
ImageJpeg($captchaImage);

The approach like: $('#someButton').click(function() { $('#someDiv').load('captcha.php'); }); suggested at PHP: Reloading the captcha image from javascript is not working. Thanks for attention.

Upvotes: 1

Views: 944

Answers (2)

Salman Arshad
Salman Arshad

Reputation: 272106

Add a random query string to the image source:

$('img.captcha_image').attr('src', $(this).attr('href') + '?rand=' + Math.random());

You should also send Cache-Control and Expires headers with the image and instruct the browser that it should not cache the image:

<?php
header("Content-Type: image/jpeg");
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");   // Date in the past
// rest of your image generation code

Upvotes: 1

toopay
toopay

Reputation: 1635

Try using more generic syntax :

$('.captcha_refresh').click(function () {
   $('.captcha_image').attr('src', $(this).attr('href'));
   return false;
});

Upvotes: 0

Related Questions