Created
March 1, 2014 23:19
-
-
Save sassman/9299147 to your computer and use it in GitHub Desktop.
django csrftoken ajax support for jquery usage: $.csrfAjaxSupport(); on load
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function ($) { | |
var cookieName = 'csrftoken'; | |
var xHeaderName = 'X-CSRFToken'; | |
var csrfSafeMethod = function (method) { | |
return /^(GET|HEAD|OPTIONS|TRACE)$/.test(method); | |
}; | |
var getCookie = function (cookie) { | |
var cookieValue = null; | |
try { | |
cookieValue = document.cookie.split(';') | |
.map(function (x) { | |
return x.trim().split('='); | |
}) | |
.filter(function (x) { | |
return x[0] == cookie; | |
}) | |
.map(function (x) { | |
return x[1]; | |
})[0]; | |
} catch (e) { | |
console.error(e); | |
} | |
return cookieValue; | |
}; | |
$.csrfAjaxSupport = function () { | |
$.ajaxSetup({ | |
crossDomain: false, | |
beforeSend: function (xhr, settings) { | |
if (!csrfSafeMethod(settings.type)) { | |
xhr.setRequestHeader(xHeaderName, getCookie(cookieName)); | |
} | |
} | |
}); | |
}; | |
}(jQuery)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment