Skip to content

Instantly share code, notes, and snippets.

@evansd
Last active August 29, 2015 13:59
Show Gist options
  • Select an option

  • Save evansd/10718888 to your computer and use it in GitHub Desktop.

Select an option

Save evansd/10718888 to your computer and use it in GitHub Desktop.
Adds support for Django's CSRF protection to jQuery's ajax method
// Adds support for Django's CSRF protection to jQuery's ajax method
(function() {
var cookieRegex = new RegExp('(?:^|;)\\s?' + 'csrftoken' + '=(.*?)(?:;|$)', 'i'),
match = document.cookie.match(cookieRegex),
csrftoken = match && decodeURIComponent(match[1]),
isSafeMethod = function(method) {
return /^(GET|HEAD|OPTIONS|TRACE)$/.test(method);
};
if (csrftoken) {
jQuery(document).ajaxSend(function(event, jqxhr, settings) {
if ( ! settings.crossDomain && ! isSafeMethod(settings.type)) {
jqxhr.setRequestHeader("X-CSRFToken", csrftoken);
}
});
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment