Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSRF with jquery and $.post in django 1.3

In django 1.3 you now have to use csrf even with ajax. I use jquery and I now want to add the csrf token to the $.post. How can i do this? I am not very skilled in jquery so it would be nice with a good description.

It is a rating app and the post is send when a star is clicked. I have seen the django docs but do not understand what to do in my situation. My code is below:

$(function() {  
            $("#avg").children().not(":input").hide();
            $("#rating-widget").children().not("select").hide();    

            $caption = $("<span/>");

            $("#avg").stars({captionEl: $caption});
            $("#rating-widget").stars({
                inputType: "select",
                cancelShow: false,
                captionEl: $caption,
                callback: function(ui, type, value){
-------------->     $.post($("#rating-widget").attr("action"), {score: value}, function(data){

                    });
                }
            });
               $caption.appendTo("#rating-widget");

});

It should be said that the javascript is not in a template but in a static file. Would it be best to put it in a template so I could use {{ csrf_token }}

Thanks in advance!

like image 657
tmpethick Avatar asked May 31 '11 23:05

tmpethick


2 Answers

Place this code before your function. It will take care of CSRF.

$('html').ajaxSend(function(event, xhr, settings) {
    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;
    }
    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
        // Only send the token to relative URLs i.e. locally.
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});
like image 161
Tomasz Karbownicki Avatar answered Nov 11 '22 07:11

Tomasz Karbownicki


In the django documentation you can find a simple description on how to automatically include the csrf token in each ajax request!

like image 3
Bernhard Vallant Avatar answered Nov 11 '22 08:11

Bernhard Vallant