Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An Easy way to submit Django Forms using Ajax jQuery

I am relatively new to Ajax and I am still trying to grasp all the concepts. I've tried to look into a bunch of tutorials for Ajax-Django form submission, most of them require jQuery forms, which doesn't seem like an easy way to handle form submission to me. I am having a hard time grasping the concept.

I am trying to write some ajax based form submissions for user registration, login, post creation and comments. And so far I havent found a way that makes it easier for me to understand how the Ajax approach would work.

I would really appreciate any help that I can get in this regard.

This is what I've tried so far.

change_pw.html

{% extends "base.html" %}
    {% block title %}Change Password{% endblock %}
    {% block head %}Change Password{% endblock %}
    {% block content %}
    {% include "modal_change_pw.html" %}
    {% endblock %}

modal_change_pw.html

<div id="modalchangepw">
<ul style="margin:5px;">
    <ul class="thumbnails" style="margin: 0 auto;background: white;">
        <div class="thumbnail row-fluid" style="background: white; padding: 10px;width: 97%; -moz-border-radius: 5px;border-radius: 5px;-moz-box-shadow:3px 3px 5px 0px #ccc;-webkit-box-shadow:3px 3px 5px 0px #ccc;box-shadow:3px 3px 5px 0px #ccc;">
            <br>
            {% if not error == '' %}
                <div class="alert alert-error">
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                    {{ error }}
                </div>
            {% endif %}
            {% if not success == '' %}
                <div class="alert alert-success">
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                    {{ success }}
                </div>
            {% endif %}
            {% if messages %}
                {% for message in messages %}
                  <div{% if message.tags %} class="alert alert-{{ message.tags }}"{% endif %}>
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                    {{ message|safe }}
                  </div>
                {% endfor %}
            {% endif %}
            <form id = 'changepw' enctype="multipart/form-data" method="post" action=".">
                <p><label for="id_currentpw">Current Password:</label> <input type="password" name="currentpw" id="id_currentpw" /></p>
                <p><label for="id_newpw1">New Password:</label> <input type="password" name="newpw1" id="id_newpw1" /></p>
                <p><label for="id_newpw2">Re-enter New Password:</label> <input type="password" name="newpw2" id="id_newpw2" /></p>
                <input class="btn btn-primary" type="submit" value="submit"/>
                {% csrf_token %}
            </form>
        </div>
    </ul>
</ul>
</div>

views.py

def change_pw(request):
    user=request.user
    error=''
    success=''
    if request.method == 'POST':
        form = ChangePw(request.POST)
        if form.is_valid():
            currentpw=form.cleaned_data['currentpw']
            newpw1=form.cleaned_data['newpw1']
            newpw2=form.cleaned_data['newpw2']
            if currentpw and newpw1 and newpw2:
                if user.check_password(currentpw):
                    if newpw1==newpw2:
                        user.set_password(newpw1)
                        user.save()
                        success='Password updated!!'
                        if request.is_ajax() :
                            messages.success(request, 'Password updated.')
                            return HttpResponseRedirect ('/changepw/')
                        else:
                            return HttpResponseRedirect ('/user/%s/' % user.username)
                    else:
                        error='New passwords do not match'
                else:
                    error='Incorrect Current Password'
            else:
                error='Enter all Password fields to make any changes' 
    else:
        form = ChangePw()
    variables = RequestContext(request, {
           'form':form,
           'error':error,
           'success':success
    })
    if request.is_ajax() :
         return render_to_response('modal_change_pw.html', variables)
    else:    
        return render_to_response('change_pw.html', variables)

forms.py

class ChangePw(forms.Form):
     currentpw = forms.CharField(
        label=u'Current Password',
        required=False,
        widget=forms.PasswordInput()
     )
     newpw1 = forms.CharField(
        label=u'New Password',
        required=False,
        widget=forms.PasswordInput()
     )
     newpw2 = forms.CharField(
        label=u'Re-enter New Password',
        required=False,
        widget=forms.PasswordInput()
     )

jQuery

//Change PW
        $('#changepw').live('submit', function(event) { // catch the form's submit event
          event.preventDefault();
          $.ajax({ // create an AJAX call...
              data: $(this).serialize(), // get the form data
              type: $(this).attr('method'), // GET or POST
              url: $(this).attr('action'), // the file to call
              success: function(response) { // on success..
                  $('#modalchangepw').html(response); // update the DIV
              }
          });
          return false;
        });

The code seems to work fine now. But my aim is to handle these forms in a modal popup fashion, so that the user doesn't have to leave the page he/she is currently on. In a modal-popup case, my form does not seem to be submitting the values.

like image 424
Jonathan Avatar asked Dec 31 '12 07:12

Jonathan


1 Answers

The AJAX concept is not a lot different from how a general form submissions work. The idea behind AJAX is to have submit(pass) the data to the server asynchronously.

How it works?

With a general form submission the flow goes somthing like this.

User submits a POST request
               ↓
Server Does the Data Processing
               ↓
Redirects to a Success or Failure Page

With ajax it works pretty similar.

User Submits a form through AJAX
               ↓
AJAX sends the POST data to the server in the background and waits for a response
               ↓
Server does the Data Processing
               ↓
and sends a Response back to AJAX
               ↓
AJAX sends the response back to the same template where the request was initiated.

Now let's have a look at a simple Ajax Login with a django view.

views.py

def ajax_login(request):
    """  
    This view logs a user in using the POST data.
    """

    if request.method == 'POST':
        data = {}
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if (not user is None) and (user.is_active):
            login(request, user)
            # Set Session Expiry to 0 if user clicks "Remember Me"
            if not request.POST.get('rem', None):
                request.session.set_expiry(0)
            data['success'] = "You have been successfully Logged In"
        else:
            data['error'] = "There was an error logging you in. Please Try again"
        return HttpResponse(simplejson.dumps(data), mimetype="application/json")

In the above view , we did the data processing and sent a JSON response back. The ajax method will look something like this.

function ajaxLogin(){
    var dataString = '&username=' + $('input[name=username]').val() +
                     '&password=' + $('input[name=password]').val() +
    $.ajax({
        type: "POST",
        url: "/ajax_login/",
        data: dataString,
        success: function(data) {
            alert(data);
        }   
     }); 
     return false;   
}

Here, the success method recieves the data back and alerts it to the user.

UPDATE

I see that you have defined the ajaxPwchange() method but i do not really see you calling it anywhere and i think that is why the page still refreshes. You can bind the ajaxPwchange() method to submit button's onclick event as follows.

<input class="btn btn-primary" type="submit" value="submit" onclick="ajaxPwchange();" />

or bind it under the document.ready method as follows:

$(document).ready(function(){
    $('input.btn-primary').click(function(){
        ajaxPwchange();
    });
});

UPDATE2

The div disappears because you are changing the div's html to a json object directly in the following code.

success: function(response) { // on success..
             $('#modalchangepw').html(response); // update the DIV
         }

you should rather try something like this :

success: function(response) { // on success..
             var jsonData = $.parseJSON(response);
             $.each(response, function(){
                 $('#modalchangepw').append('<div class="message">' + $(this) + '</div>');
             });
         }
like image 169
Amyth Avatar answered Oct 12 '22 22:10

Amyth