beforeSend in $.ajaxSetup + beforeSend in $.ajax

ajax, jquery

Solution

Use `$(document).ajaxSend(function(ev, jqhr, settings) { ... })` instead of `.ajaxSetup`.

As you said `.ajaxSetup` defines a default handler which then can be overriden. With `.ajaxSend` you can register multiple handlers to fire before an ajax request is sent. Works fine with custom `beforeSend` handler.

Problem

To solve the CSRF problem, I use a client-side setup for Ajax: ``` $.ajaxSetup({ beforeSend: function(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; } if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { // Only send the token to relative URLs i.e. locally. xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } }); ``` Until today, everything worked fine. But now I need to do some check before post: ``` var check; //... $.ajax({ //... beforeSend: function(xhr){ if (check == 1){ xhr.abort(); } }, success: function(data){ //... } }); ``` Have CSRF verification failed. Request aborted. As I understand it, I just cancel the action of ajaxSetup for the new function. How to combine these two things?

Original source