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'));
}
});