Search code examples
javascriptajaxdjangocsrf-protection

JQuery + AJAX + Django = CSRF ?


Possible Duplicate:
"CSRF token missing or incorrect" while post parameter via AJAX in Django

I wanted to send login data by AJAX to authenticate user, but it wasn't possible because of CSRF. Could You tell me what to add to my code to make it woking?

my JavaScript file:

$("#login").live("click", function() {
    var username = $(".login_username").val();
    var password = $(".login_password").val();

    $.ajax({
        url: "/login",
        type: "POST",
        data: {
            username: username,
            password: password
        },
        cache: false,
        success: function(tekst) {
            alert(tekst);
        }
    });
});

Solution

  • There is a method explained here.

    It consists of adding a X-CSRFToken header on each ajax request.

    This is done by hooking in the jQuery.ajaxSend event, so everything is done automatically (you just have to copy and past their code, and run it once before the first ajax request you make).