Changing Password in Django using Jquery/Ajax

I posted about this not so long ago without using JQuery/Ajax, here is the link.This time, with different approach and much easier.All you need to do is create function in then use it in and call the URL using Ajax.


<form action="/change_pw/" method="post" id="frmChangePW">
  {% csrf_token %}
  <div class="form-group">
    <label for="id_old_password">Old Password:</label>
    <input class="form-control" id="id_old_password" name="old_password" type="password" placeholder="Old Password" autofocus="">
  <div class="form-group">
    <label for="id_new_password">New Password:
      <input class="form-control" id="id_new_password" name="new_password" placeholder="New Password" type="password">
    <label for="id_re_new_password">Re-type New Password:
      <input class="form-control" id="id_re_new_password" name="re_new_password" placeholder="Re-type New Password" type="password">
  <input type="submit" id="btnUpdate" value="Update" class="btn btn-primary">


var frmPW = $('#frmChangePW');
frmPW.submit(function() {
    type: frmPW.attr('method'),
    url: frmPW.attr('action'),
    data: frmPW.serialize(),
    success: function(resp) {
      $("#respp").html('<strong><p class="text-info">' + resp + '</p></strong>').show().fadeOut(3000);
    error: function() {
      $("#respp").html('<strong><p class="text-danger">Error!</p></strong>').show().fadeOut(3000);
  return false;

 url(r'^change_pw/$', '<app_name>.views.change_pw'),

def change_pw(request):
    uname = request.user.username
    message = {}
    if request.method == 'POST':
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        retype_new_password = request.POST.get('re_new_password')
        user = authenticate(username=uname, password=old_password)
        if user is not None:
            if new_password == retype_new_password and new_password != '':
                u = User.objects.get(username=uname)
                message = 'Successfully Changed the Password.'
                message = 'Invalid Passwords!'
            message = 'Invalid Password!'
    return HttpResponse(json.dumps(message), content_type='application/json')


Popular posts from this blog

Set table width to 100% on PDF export in Datatables

Add/Subtract Single Digit Number in Assembly Language