Permalink
Browse files

Add note on ajax

Fixes #11
  • Loading branch information...
1 parent 2f5d695 commit 2e4df4c141ff9be9a7af009b1eaf83faca66a095 @paltman paltman committed Jan 2, 2013
Showing with 53 additions and 1 deletion.
  1. +52 −0 docs/ajax.rst
  2. +1 −1 docs/index.rst
View
@@ -0,0 +1,52 @@
+.. _ajax:
+
+AJAX
+====
+
+It's quite common to have this snippet already included in a site and there
+are a few different variations, but to avoid exempting CSRF checks for the
+POST, you'll want something like this included in your base template.
+
+If you don't have this already (or something similar), considering creating
+a ``ajax.js`` file with the following contents::
+
+ $(document).ajaxSend(function(event, xhr, settings) {
+ 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;
+ }
+ function sameOrigin(url) {
+ // url could be relative or scheme relative or absolute
+ var host = document.location.host; // host + port
+ var protocol = document.location.protocol;
+ var sr_origin = '//' + host;
+ var origin = protocol + sr_origin;
+ // Allow absolute or scheme relative URLs to same origin
+ return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
+ (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
+ // or any other URL that isn't scheme relative or absolute i.e relative.
+ !(/^(\/\/|http:|https:).*/.test(url));
+ }
+ function safeMethod(method) {
+ return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
+ }
+
+ if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
+ xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
+ }
+ });
+
+And including it::
+
+ <script src="{% static "js/ajax.js" %}"></script>
View
@@ -21,4 +21,4 @@ Contents
templatetags
signals
usage
-
+ ajax

0 comments on commit 2e4df4c

Please sign in to comment.