In my django application, I am trying to use ajax to check if a username exists and displays an error if so.
That's what i
HTML:
<form method="post" id='my_form'> {% csrf_token %} <input id='username' type="text" name="username"/> <button type="submit">Valider</button> </form>
JS:
$('#my_form').submit(function(){ var username = $('#username').val(); if (username == ''){ alert('please enter username'); return false; } $.ajax({ type: "POST", url: "/auth_validate", data: {'username': $('#username').val(), 'csrfmiddlewaretoken': '{{csrf_token}}'}, dataType: "text", success: function(response) { var response = $.parseJSON(response); if (response.success){ return true; } else{ alert(response.error); return false; } }, error: function(rs, e) { alert(rs.responseText); return false; } }); })
Views:
def auth_validate(request): error = '' success = False if request.method == 'POST': username = request.POST.get('username', None) if not username: error = _('Please enter username') elif User.objects.filter(username__exact=username).exists(): error = _('Sorry this username is already taken') else: success = True ajax_vars = {'success': success, 'error': error} return HttpResponse(simplejson.dumps(ajax_vars), mimetype='application/javascript')
When I enter the username (if it exists or not), an empty warning appears, and when I click "ok", the form is submitted. In addition, errors are not displayed.
Any idea on why it doesn't work?
Thank you for your help.
source share