tags:

views:

202

answers:

2

I wrote my own php captcha script, with a jpeg header, so that I can say

<img src="captcha.php">

which works by storing the value of the captcha into the session variable. When the user can't read it, I want it to be refreshable.

I first tried

$("#refresh").click(function() {
    $("#captcha").attr("src","captcha.php");
});

but of course that doesn't make sense, and I need to make an ajax call instead. How would you all recommend I do this?

P.S. I also tried

$.ajax({
    url: "captcha.php",
    success: function(result) {
        $("#captcha").attr("src",result);
    }
});
A: 

It makes sense to store the actual CAPTHCHA string in the _SESSION variable, but you should explicitly specify the state in the URL:

$.ajax({
    url: "captcha.php?generateNew",
    success: function(result) {
        $("#captcha").attr("src","captcha.php?foo="+Math.random());
    }
});

inside your php-file:

if(isset($_GET['generateNew']){
    $_SESSION['captchaString'] = generateCaptchaString();
}else{
    dumpCaptchaImage();
}
geon
+1  A: 

The first method actually makes sense to me:

$("#refresh").click(function() {
    $("#captcha").attr("src","captcha.php?r=" + Math.random());
});

I assume the only thing captcha.php does is store the captcha value in session variable and outputs the captcha image, whenever its accessed.

So when you set the src of the image again and add a query string variable to it, a request is gonna be sent to the server script "captcha.php" again, which is going to then regenerate the captcha and store the new value in the session variable.

ovais.tariq