r3wt
r3wt

Reputation: 4742

$.ajaxPrefilter overwrites request body

I wanted to add a csrf token to all request bodies for ajax requests. i found the following post useful: jQuery add CSRF token to all $.post() requests' data

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
    options.data = $.param($.extend(originalOptions.data, { c: csrf }));
});

For some reason, this ovewrites the request body. i do not understand why. i can see when i serialize the request body its all there, but when it submits the body only contains the c field. It may be helpful to note that i am creating the form data using jQuery's serialize() method.

Upvotes: 2

Views: 943

Answers (1)

Kevin B
Kevin B

Reputation: 95066

The code you found isn't working because it was built specifically for handling data that was passed in as an object rather than a param string.

There is however a much easier way of accomplishing this goal that won't be affected by how the data is passed in:

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
    if (options.processData && options.contentType === 'application/x-www-form-urlencoded; charset=UTF-8') {
        options.data = (options.data ? options.data + '&' : '') + $.param({ c: csrf });
    }
});

So instead of modifying the original object and adding a value, or converting the param string back to an object just to re-parse it, we param the new value we want to send and append it to the param string, only if processData is true and the contentType is set to default (to avoid mangling other content types.)

Upvotes: 2

Related Questions