Search code examples
jqueryajaxdjangocsrfdjango-csrf

Django ajax POST extend beforeSend method used for CSRF protection


I do need to make same ajax POST calls in Django. So I use the method described in Django docs:

function csrfSafeMethod(method) {
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    crossDomain: false, 
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

However, when I make ajax calls and want to add some action for beforeSend method (i.e. display loader image), it removes the above function. Example:

$.ajax({
    url: "some_url",
    type: "POST",
    data: some_form.serialize(),
    beforeSend: function() { some_element.showLoader();}
});
$.ajax({
    url: "some_other_url",
    type: "POST",
    data: some_other_form.serialize(),
    beforeSend: function() { some_other_element.showLoader();}
});

DRY is important and I don't want to put the "showLoader()" function in ajaxSetup, cause it may differ.


Solution

  • Ok, never mind, I found a solution. Just use ajaxSend():

    $(document).ajaxSend(function(event, xhr, settings){
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    });