简体   繁体   中英

ajax in django success function is not working

I am new in ajax as well as Django. I try to put ajax in my code to check that in the signup page if some user is already having one email then that email can't use for new users and disable the button else if the email does not exist then the user can be created.

ajaxCode


$(document).on('blur', 'input[name="email"]', function(){
   $.ajax({
    type:'POST',
    url:'/stock/checkemail/',
    data:{
        email:$("#email").val(),
        csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
    },
    success:function(){
        $('input[type="submit"]').attr('disabled', 'true')
    },
    failure:function(){
        $('input[type="submit"]').removeAttr('disabled');
    }
   })
});

url.py

    path('checkemail/',Emailser.as_view()),

views.py

class Emailser(View):
    def post(self, request):
        em = request.POST['email']
        print(em)
        try:
            user = User.objects.get(email=em)
            return HttpResponse('true')
        except:
            return HttpResponse('false')

In views.py print(em) is also printing mail that type in field but don't know why is not working. template

{% extends 'base.html' %}
{% block content %}
{% load static %}
<div>
  <h2>Sign Up</h2>
  {% if error %}
{{error}}
<br/>
{% endif %}
  <form method="post" id="signup" >
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="btn btn-primary" >Signup</button>
  </form>
</div>
     <script src="{% static 'assets/signup.js' %}" ></script>
{% endblock %}

try this inside succcess function

$('input[type="submit"]').disabled = true;
$(document).on('blur', 'input[name="email"]', function(){
   $.ajax({
    type:'POST',
    url:'/stock/checkemail/',
    data:{
        email:$("#email").val(),
        csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
    },
    success:function(response){
        response ? $('input[type="submit"]').attr('disabled', 'true') :  $('input[type="submit"]').removeAttr('disabled');

    },
    failure:function(error){
     console.log(error);
    }
   })
});

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