Skip to content

Commit fd8ae06

Browse files
Add django-csrf.js to support csrf protected POST requests.
1 parent 6d7733d commit fd8ae06

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

media/javascript/django-csrf.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
(function () {
2+
function csrfSafeMethod(method) {
3+
// these HTTP methods do not require CSRF protection
4+
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
5+
}
6+
7+
$.ajaxSetup({
8+
beforeSend: function(xhr, settings) {
9+
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
10+
function getCookie(name) {
11+
var cookieValue = null;
12+
if (document.cookie && document.cookie != '') {
13+
var cookies = document.cookie.split(';');
14+
for (var i = 0; i < cookies.length; i++) {
15+
var cookie = jQuery.trim(cookies[i]);
16+
// Does this cookie string begin with the name we want?
17+
if (cookie.substring(0, name.length + 1) == (name + '=')) {
18+
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
19+
break;
20+
}
21+
}
22+
}
23+
return cookieValue;
24+
}
25+
var csrftoken = getCookie('csrftoken');
26+
27+
xhr.setRequestHeader("X-CSRFToken", csrftoken);
28+
}
29+
}
30+
});
31+
})();

0 commit comments

Comments
 (0)