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!
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'));
    }
});
                        In the django documentation you can find a simple description on how to automatically include the csrf token in each ajax request!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With