Sunday, March 26, 2017

Django Captcha Ajax call not working

I have the following class view taken from documentation:

class CaptchaView(CreateView):
    template_name = "captcha.html"
    form_class = MyForm
   
    def form_invalid(self, form):
        if self.request.is_ajax():
            to_json_response = dict()
            to_json_response['status'] = 0
            to_json_response['form_errors'] = form.errors

            to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
            to_json_response['new_cptch_image'] = captcha_image_url(to_json_response['new_cptch_key'])

            return HttpResponse(json.dumps(to_json_response), content_type='application/json')
        else:
            return HttpResponse("test1", content_type='application/json')

    def form_valid(self, form):
        if self.request.is_ajax():
            to_json_response = dict()
            to_json_response['status'] = 1

            to_json_response['new_cptch_key'] = CaptchaStore.generate_key()
            to_json_response['new_cptch_image'] = captcha_image_url(to_json_response['new_cptch_key'])

            return HttpResponse(json.dumps(to_json_response), content_type='application/json')
        else:
            return HttpResponse("test2", content_type='application/json')


and the following ajax call from template:

    <script type="text/javascript">
        function captcha() {
            $.ajax({
                type: "POST", 
                url: "../captcha",
                contentType: "application/json",
                data: {},
                dataType: "json",
                success: function(data) {
                    alert("success");
                  },
                error: function(data) {
                    alert("not OK");
                  }

                });
        }
    </script>


<input type="button" id="button" onclick="captcha()" value="OK"/>

url(r'^captcha$', views.CaptchaView.as_view(), name="captcha")

Could you please help me to get a proper ajax call? When i click the OK button no success or error message is displayed!!!

Please help me out!!

thanx

valerio


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/2877f6c0-928a-47e1-8398-f57ef3200aba%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment