Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Ajax refresh for django-simple-captcha

Tags:

django

captcha

I'm using the django-simple-captcha app for my django based website, I am able to integrate the captcha form field into my form, but the problem is, how do I create a button which calls Ajax refresh to refresh the captcha image on click? The documentation for the app is not very clear, and I tried to follow the example given in the documentation but it doesn't work. Please help me on this issue?

EDIT: Here's the link to the django package: django-simple-captcha

like image 769
csharpnewbie Avatar asked Sep 24 '13 03:09

csharpnewbie


1 Answers

Here's a working implementation in javascript:

$(function() {
    // Add refresh button after field (this can be done in the template as well)
    $('img.captcha').after(
            $('<a href="#void" class="captcha-refresh">Refresh</a>')
            );

    // Click-handler for the refresh-link
    $('.captcha-refresh').click(function(){
        var $form = $(this).parents('form');
        var url = location.protocol + "//" + window.location.hostname + ":"
                  + location.port + "/captcha/refresh/";

        // Make the AJAX-call
        $.getJSON(url, {}, function(json) {
            $form.find('input[name="captcha_0"]').val(json.key);
            $form.find('img.captcha').attr('src', json.image_url);
        });

        return false;
    });
});

Then you just need to add some CSS for the class captcha-refresh, perhaps place an image in the <a> and you're good to go!

like image 113
MW. Avatar answered Oct 17 '22 18:10

MW.