Django Ajax Jquery Call


Question

This may be basic, but I've spent two days, read countless tutorials and I still can not get this to work. For simplicitly I tried to accomplish a basic task just to see it work. I want to send make an ajax call to my donate view. I see that it successfully passes through but I was expecting that my template would also get updated to "TRUE" but it remains "FALSE". Any help or suggestions I appreciate.

my jquery...

$.ajax({
    type: "POST",
    url:"/donate/",
    data: {
    'test': 'success',
    },
    success: function(){
      alert('test')
     },
    error: function(){
        alert("Error");
});

this is my view...

def donate(request):
    if request.is_ajax():
        test = "TRUE"

    if request.method == 'POST':
        form = DonateForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = DonateForm()
        test = "FALSE"

    return render_to_response('donate_form.html', {'form':form,'test':test}, context_instance=RequestContext(request))

my template include this...

<h1>{{ test }}</h1>

Update/Solution

Like mentioned in the comments on this question, I was not doing anything the the returned data. I updated my success call to the following and it worked

    $.ajax({
    type: "POST",
    url:"/donate/",
    data: {
    'zip': zip,
    },
    success: function(data){            

        results = $(data).find('#results').html()               
        $("#id_date").replaceWith("<span>" + results + "</span >");

    },
    error: function(){
        alert("Error");
    },
1
7
5/2/2012 2:51:02 AM

Accepted Answer

I think the problem is at where you pass the data. Do you use Firebug? An excellent tool for checking if you pass anything in POST, it is an excellent tool for web development in general.

Here's a working example for sending Ajax call from a form

$("#form").submit(function(event) {
        var $form = $(this),
        $inputs = $form.find("input, select, button, textarea"),
        serializedData = $form.serialize();

        $.ajax({
            url: "/donate/",
            type: "post",
            data: serializeData,
            success: function(response) {
                alert(response)
            }
        })
        event.preventDefault();
    });

and then your view can look something like this

if request.is_ajax() or request.method == 'POST':
        form = DonateForm(data=request.POST)
        if form.is_valid():
            return HttpResponse("Success")
        else:
            return HttpResponse("Fail")

Btw, unless you really need all the extras from $.ajax() I would suggest you to use $.post() instead as it seems more straight forward to use.

12
4/29/2012 9:03:05 AM

I think there are few things that are wrong with your code...

  1. You are sending a POST request to django without csrf_token => django will not return a success for this request. You need to send csrf_token with POST request. Check with firebug.

  2. Even if django is not giving any error then you are not changing the content of your page (on browser) anywhere... djang will send back this string -> "success" ...that's all.

You need to change your code like this,

add 'django.core.context_processors.csrf' to TEMPLATE_CONTEXT_PROCESSORS in settings.py to get access to csrf token in all templates.

your current template:

<html>
    <script type="text/javascript">
    $("#form").submit(function(e) {
        e.preventDefault();
        serializedData = $("#form").serialize();

        $.ajax({
           url: "/donate/",
           type: "post",
           data: serializeData,
           cache: 'false',
           dataType: "json",
           async: 'true',

           success: function(data) {
               alert(data)
           },
           error:function(data) {
               alert("error in getting from server")
           },
        });
    });  
    </script>
    <body>
        <form id="form">
            {% csrf_token %}
            {% for field in form %}
                {{ field }}
            {% endfor %}
        </form>
    <body>
</html>

donate view:

def donate(request):
    if request.method == 'POST':
        form = DonateForm(data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponse("SuccessFully Saved")
        else:
            return HttpResponse("Error in saving")

Now, you will see :

  • SuccessFully Saved -> if successfuly saved data.
  • Error in saving -> If data not saved for some reason.
  • error in getting from server -> if server responded with some error.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon