$ ajax and Json answer

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.

0
source share
3 answers

Your look and template look great. I suggest you use the built-in JSON function handling and serialization of the form instead of manually β€œsending” the data . Also note the return false at the end of the event callback, and not 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 else in the success callback;)

+2
source

Because of this part:

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

the answer does not matter "success", so a pop-up dialog box appears. jQuery already takes care that this check is only performed when the request was successful, so you should not do this.

If you do not want to use browser submission in the browser, add return false; at the end of your function to prefix the default browser behavior.

+1
source

How does JSON look like django is responding?

Do you know what warning is triggered? Is this a function of error or a function of success?

I do not think you need this line

 var response = $.parseJSON(response); 

The answer should already be JSON.

0
source

All Articles