Peeter
Peeter

Reputation: 9382

Adding a general parameter to all ajax calls made with jQuery

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?

Upvotes: 16

Views: 10537

Answers (4)

Raja Khoury
Raja Khoury

Reputation: 3195

An example using ajaxPrefilter to extend posted data :

$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
    if ((originalOptions.type + "").toLowerCase() == "post" || (options.type + "").toLowerCase() == "post") {
        var modifiedData = $.extend({},originalOptions.context.options.data,{ property:"val",property_two: "val" });
        options.context.options.data = modifiedData;
        options.data = $.param(modifiedData,true);
    } 
});

Upvotes: 2

Joost00719
Joost00719

Reputation: 754

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);
        }
    });

Upvotes: 0

Maurício Linhares
Maurício Linhares

Reputation: 40323

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.

Upvotes: 10

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

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

Upvotes: 16

Related Questions