Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to response ajax request in Django

Tags:

python

django

I have code like this:

$(document).ready(function(){
    $('#error').hide();
    $('#submit').click(function(){
        var name = $("#name").val();
        if (name == "") {
            $("#error").show("slow");
            return false;
        }
        var pass = $("#password").val();
        if (pass == "") {
            $("#error").show("slow");
            return false;
        }
        $.ajax({
            url: "/ajax/",
            type: "POST",
            data: name,
            cache:false,
            success: function(resp){
                alert ("resp");
            }
        });
    });
});

and view in Django:

def lat_ajax(request):
    if request.POST and request.is_ajax:
        name = request.POST.get('name')
        return HttpResponse(name)
    else :
        return render_to_response('ajax_test.html',locals())

Where is my mistake? I'm a beginner in Django, please help me.

like image 291
CitooZz Banditozz Avatar asked Feb 01 '13 08:02

CitooZz Banditozz


People also ask

How send data from AJAX to Django?

To send and receive data to and from a web server, AJAX uses the following steps: Create an XMLHttpRequest object. Use the XMLHttpRequest object to exchange data asynchronously between the client and the server. Use JavaScript and the DOM to process the data.

Does AJAX work with Django?

Using Ajax in Django can be done by directly using an Ajax library like JQuery or others. Let's say you want to use JQuery, then you need to download and serve the library on your server through Apache or others. Then use it in your template, just like you might do while developing any Ajax-based application.


1 Answers

Put dataType: "json" in the jquery call. The resp will be a javascript object.

$.ajax({
    url: "/ajax/",
    type: "POST",
    data: name,
    cache:false,
    dataType: "json",
    success: function(resp){
        alert ("resp: "+resp.name);
    }
});

In Django, you must return a json-serialized dictionnary containing the data. The content_type must be application/json. In this case, the locals trick is not recommended because it is possible that some local variables can not be serialized in json. This wil raise an exception. Please also note that is_ajax is a function and must be called. In your case it will always be true. I would also test request.method rather than request.POST

import json
def lat_ajax(request):

    if request.method == 'POST' and request.is_ajax():
        name = request.POST.get('name')
        return HttpResponse(json.dumps({'name': name}), content_type="application/json")
    else :
        return render_to_response('ajax_test.html', locals())

UPDATE : As mentioned by Jurudocs, csrf_token can also be a cause I would ecommend to read : https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

like image 58
luc Avatar answered Sep 30 '22 21:09

luc