Pinkie Pie
Pinkie Pie

Reputation: 71

Django/AJAX/JQuery - Unable to receive a POST response

Ok, first of all, I'm a JQuery/AJAX noob, but I can manage to get around most of the time.

Here's the problem.

For some reason everytime I use POST as the AJAX type I don't get a response, but when I use GET I do get a response.

Why is this happening and how do I fix it.

HTML

<form action="/trivia/ajax_test/" method="post" onsubmit="return ajaxTest()">
{% csrf_token %}
<button type="submit">AJAX</button>
</form>

JQuery/AJAX

function ajaxTest() { 
    $.ajax({
        type: 'POST', // Works with 'GET', but failing with 'POST'
        url: '/trivia/ajax_test/',
        data: {some_text: 'The test is working'},
        success: function(result){alert(result);} 
    });

    return false;
}

URLS

(r'^trivia/ajax_test/$', 'findadownload.trivia.views.ajax_test'),

VIEWS

def ajax_test(request):
    if request.is_ajax():
        return HttpResponse("Success")

    else:
        result = "You went to the url directly"

    return HttpResponse(result)

Upvotes: 3

Views: 375

Answers (1)

Matt
Matt

Reputation: 10312

This is because of the CSRF protection built into Django.

Add this to your Javascript, before your Ajax call or disable CSRF protection for your POST view.

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    crossDomain: false, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

Upvotes: 2

Related Questions