简体   繁体   中英

Use jQuery's ajax call to refresh a captcha

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?

PS I also tried

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM