$ ajax命令和Json响应

In my django app I try to use ajax in order to check if a username already exists and display an error if it is the case.

Here is what I have

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 a username (if it exists or not) an empty alert appears and when I click on 'ok', the form is submitted. Moreover, the errors do not appear.

Any idea on why it doesn't work?

Thank you for your help.

What does the JSON look like that django is responding with?

Do you know which alert is getting called? Is it the one in the error function or the success function?

I don't think you need this line

var response = $.parseJSON(response);

the response should already be JSON.

Because of this part:

         var response = $.parseJSON(response);
          if (response.success){
              return true;
          }
          else{
              alert(response.error);
          }

response doesn't have a value 'success', so an emply alert dialog pops up. jQuery already takes care, that this check is only done when the request was sucesssful, so you don't to do it.

If you don't want to use the browser submit of the for, add return false; at the end of your funciton to prefent the browser default behavior.

Your view and template look fine I suggest that you use the native JSON handling the function has and serialize the form instead of "sending" data manually. Also please note the return false at the end of the event callback, instead of inside the success and error callbacks.

$('#my_form').on('submit', function(){
    var $form = $(this);
    $.ajax({
        type: "POST",
        url: "/auth_validate",
        data: $form.serialize(),
        dataType: "json",
        success: function(response) {
            if (!response.success) {
                alert(response.error);
            } else {
                alert('This username is available!');
            }
        },
        error: function(rs, e) {
            alert(rs.responseText);
        }
    });
    return false;
});

Good luck :)

UPDATE:

Please check the else in the success callback ;)