Masoud Masoud - 2 months ago 16
Ajax Question

refreshing captcha code using Ajax

In my page I have an

img
that shows
captcha
code and one
img
that refreshes the
captcha
code, not whole page, when clicked. in
chrome
it works very well and refreshes the code every time it is clicked, but in
IE
nothing happens when the
img
is clicked and for refreshing the
captcha
code you have to reload the page.

how can I solve this problem in
IE
?

<img name="capImg" id="capImg" src="php/captcha.php">
<img src="images/recaptcha.png" onClick="resetCap();">


script:

function resetCap(){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
document.getElementById('capImg').src = "php/captcha.php";
}
}
ajaxRequest.open("GET", "php/captcha.php", true);
ajaxRequest.send();
}


captcha.php:

<?php
session_start();
$backImage = imagecreatefrompng('C:\xampp\htdocs\service\images\captchaBack.png');
$shadowColor = imagecolorallocate($backImage, 150, 150, 150);
$textColor = imagecolorallocate($backImage, 50, 50, 50);
$font_path = 'C:\xampp\htdocs\service\fonts\times_new_yorker.ttf';
$text = NULL;
for($i=0; $i<6; $i++) $text .= mt_rand(0,9);
$_SESSION['capCode'] = $text;
imagettftext($backImage, 28, 2, 13, 38, $shadowColor, $font_path, $text);
imagettftext($backImage, 28, 2, 15, 40, $textColor, $font_path, $text);

header('Content-type: image/png');

imagepng($backImage);
imagedestroy($backImage);
?>

Answer

Use a unique parameter that will make browser retrieve the image again and not look into the cache. You don't need Ajax here:

function resetCap(){
    document.getElementById('capImg').src = 
                           "php/captcha.php?" + new Date().getTime();  
}

This is all you need.

Comments