16

I'm using AJAX to load data from the server as needed. I'm currently working on updating the server software to the latest version. One of the things I noticed that has changed is that every request now requires me to pass along a token. This means I have to add a new parameter to every request. I'm hoping to achieve this by a general method, without having to modify every single AJAX call.

Any pointers?

Peeter
  • 9,282
  • 5
  • 36
  • 53

4 Answers4

17

You could use the $.ajaxSetup method as illustrated in the following article.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
10

What you're looking for is a Prefilter, here's a sample from the page:

$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
  // Modify options, control originalOptions, store jqXHR, etc
});

This requires JQuery 1.5.

Jace Rhea
  • 4,982
  • 4
  • 36
  • 55
Maurício Linhares
  • 39,901
  • 14
  • 121
  • 158
  • If you're passing a string vs. object, you will need to use prefilter to append the parameter. We have this: beforeSend: function(jqXHR, settings) {settings.data = settings.data+'&foo=bar'; return true; } – Vael Victus Mar 13 '15 at 17:52
  • Thanks I found this more handy and more generic – John-Philip Nov 08 '16 at 12:41
0

An example using ajaxPrefilter to extend posted data :

$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
    if (originalOptions.type === 'POST' || options.type === 'POST') {
        var modifiedData = $.extend({},originalOptions.context.options.data,{ property:"val",property_two: "val" });
        options.context.options.data = modifiedData;
        options.data = $.param(modifiedData,true);
    } 
});
Raja Khoury
  • 3,015
  • 1
  • 20
  • 19
0

I took Raja Khoury's solution, but edited it a bit since context was null in my case.

This is what I came up with:

    $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
        if (originalOptions.type === 'POST' || options.type === 'POST') {
            var modifiedData = $.extend({}, originalOptions.data, { __RequestVerificationToken: getAntiForgeryToken() });
            options.data = $.param(modifiedData);
        }
    });
Joost00719
  • 716
  • 1
  • 5
  • 20