Skip to content

Instantly share code, notes, and snippets.

@o3bvv
Created January 12, 2015 15:09
Show Gist options
  • Save o3bvv/a6af6fa163d854779e2b to your computer and use it in GitHub Desktop.
Save o3bvv/a6af6fa163d854779e2b to your computer and use it in GitHub Desktop.
Setup Django's CSRF for AJAX
function get_cookie(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])
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1))
break
}
}
}
return cookieValue
}
$.ajaxSetup({beforeSend: function(xhr, settings){
xhr.setRequestHeader('X-CSRFToken', get_cookie('csrftoken'))
}})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment