[Fixed]-An Easy way to submit Django Forms using Ajax jQuery

36👍

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>');
             });
         }
👤Amyth

10👍

I’ll give you a very easy example so that you can grasp the concept and then use that same concept to do what you’re trying to do.

I would start by creating a normal view in views.py

def MyAjaxView(request):
    if request.is_ajax():
         if request.method == 'GET':
             # If it was a GET
             print request.GET
         elif request.method == 'POST':
             # Here we can access the POST data
             print request.POST
    else:
         doSomeOtherStuff()
    return render_to_response('mytemplate.html', some_context_maybe, context_instance=RequestContext(request))

Depending on what you already use or what you are allowed to use you would call this using javascript or the library jQuery.

Assuming you have a form that looks like this

<form id="myNameForm">
   {% csrf_token %}
   <input type="text" id="name" />
   <input type="submit" value="submit" id="submitButton" />
</form>

you can now hook this up to an ajax function using JavaScript, I’ll be using jQuery as demonstration and I’ll use the jQuery method ajax() as it explains the concept and moving on to post() shouldn’t be all too difficult.

<script>
    $('#submitButton').click(function(event){
         event.preventDefault(); //so that we stop normal form submit.
         $.ajax(
             url: 'myViewUrl',
             type: 'post',
             dataType: 'json',
             data: $('form#myNameForm').serialize(),
             success: function(data) {
               doStuffWithDataHere(data);
             }
         );
    });
</script>

You have to make sure that your urls.py have a url mapping to your new view.
Using the CSRF protection also requires to use the CSRF processor, see BurhanKhalids comment for documentation.

Leave a comment