Skip to content

Instantly share code, notes, and snippets.

@wezleysherman
Created January 25, 2020 02:20
Show Gist options
  • Save wezleysherman/d278ac557511140143d3b73ddb14e1c5 to your computer and use it in GitHub Desktop.
Save wezleysherman/d278ac557511140143d3b73ddb14e1c5 to your computer and use it in GitHub Desktop.
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
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;
}
var csrftoken = getCookie('csrftoken');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment