extend all ajax post with jquery

393
November 28, 2016, at 9:39 PM

I need to extend all my ajax posts with a csrf token from cookies. I've tried following:

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
        if(options.type.toUpperCase() === "POST")
        options.data = options.data || {};
        $.extend(options.data, { csrf: $.cookie('cookiename') });
    });

But it doesn seem to get applied to any of my existing posts. My console returns:

Blocking Post Request: no csrf token parameter

If i console.log following:

console.log($.cookie('CSRF'), 'waah');

It logs fine. Any ideas?

Answer 1

That's because options.data is not object, it's query string and that's why you can't merge two objects.

You should to append parameters to query string, something like this:

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    if(options.type.toUpperCase() === "POST") {
        options.data += options.data ? '&' : '';
        options.data += 'csrf=' + $.cookie('CSRF');
    }
});
Answer 2

You can change the following line :

$.extend(options.data, { csrf: $.cookie('cookiename') });

By this one :

options.data = $.param( $.extend(originalOptions.data, { csrf: $.cookie('cookiename') }) );

Note : By default options.data is a String and not an Object instead of originalOptions.data.

Hope this helps.

Rent Charter Buses Company
READ ALSO
jQuery loop over list items and get the data-imgid attribute value [closed]

jQuery loop over list items and get the data-imgid attribute value [closed]

There are several li elements with a data-id attribute like

370
count element after load

count element after load

I would like counting the total number of element on my page, after which the new element has been loaded

386
javascript, array of string as JSON

javascript, array of string as JSON

I'm having problems with passing two arrays of strings as arguments in JSON format to invoke ASMX Web Service method via jQuery's "POST"

441
How to change REL attribute to other

How to change REL attribute to other

I have a problem with W3 validatorHere is the code:

281