2 * Django CSRF protection for Ajax requests. This script adds a CSRF token to
3 * all POST requests sent using jquery ajax functions. This ensures that all
4 * POST requests will be proected even when they do not submit a form.
6 * This script expects that DOMAIN is set to the domain & port of the host
7 * e.g. "localhost:8000"
10 $(document).ready(function() {
11 $('html').ajaxSend(function(event, xhr, settings) {
12 function getCookie(name) {
13 var cookieValue = null;
14 if (document.cookie && document.cookie != '') {
15 var cookies = document.cookie.split(';');
16 for (var i = 0; i < cookies.length; i++) {
17 var cookie = jQuery.trim(cookies[i]);
18 // Does this cookie string begin with the name we want?
19 if (cookie.substring(0, name.length + 1) == (name + '=')) {
20 cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
28 // Only send the token locally. Check for both relative urls, and
29 // absolute urls to the domain.
30 var url = settings.url;
31 var absolute_https = new RegExp("^https:\/\/"+window.location.host+"\/.*");
32 var absolute_http = new RegExp("^http:\/\/"+window.location.host+"\/.*");
34 !(/^http:.*/.test(url)|| /^https:.*/.test(url))
35 || (absolute_https.test(url) || absolute_http.test(url))
37 xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));