Commits

Luke Plant committed ec7cb32

[1.1.X] Fixed #15284 - improved example jQuery code for adding X-CSRF-Token

Using the ajaxSend event is better than beforeSend, because the beforeSend
callback can have only one value, which makes it painful if it is needed by
multiple bits of javascript.

Thanks to LukeMaurer for report and initial patch.

Backport of [15515] from trunk.

This is backported to 1.1.X because it really belongs with security patch [15466]

Comments (0)

Files changed (1)

docs/ref/contrib/csrf.txt

 there is an alternative method: on each XMLHttpRequest, set a custom
 `X-CSRFToken` header to the value of the CSRF token. This is often easier,
 because many javascript frameworks provide hooks that allow headers to be set on
-every request. In jQuery, you can use the ``beforeSend`` hook as follows:
+every request. In jQuery, you can use the ``ajaxSend`` event as follows:
 
 .. code-block:: javascript
 
-    $.ajaxSetup({
-        beforeSend: function(xhr, settings) {
-            if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
-                // Only send the token to relative URLs i.e. locally.
-                xhr.setRequestHeader("X-CSRFToken",
-                                     $("#csrfmiddlewaretoken").val());
-            }
+    $('html').ajaxSend(function(event, xhr, settings) {
+        if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
+            // Only send the token to relative URLs i.e. locally.
+            xhr.setRequestHeader("X-CSRFToken",
+                                 $("#csrfmiddlewaretoken").val());
         }
     });