Snake Eyes Snake Eyes - 29 days ago 11
jQuery Question

Modify data property for every ajax request and type POST using jQuery

I have the following ajax call used in different situation:

$.ajax({
url: '...',
type: "POST"
data: {val: '1', test: 'test1' },
...
});


I want, for every ajax start and for "POST" method only, to add a parameter to
data
property.

I used this:

$(document).ajaxStart(function(){
//if type is POST then
// data.myProp = 1; or similar
});


How to get
data
and
type
from ajaxStart ?

EDIT

If I use ajax.preFilter then will not work fine.

So:

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
if (originalOptions.type === 'POST' || options.type === 'POST') {
options.data = $.extend(originalOptions.data, { myProp : 1});
}

});


and then:

$.ajax({
...,
data: { myItem: 'tes' },
...
});


then
data
will not contain
myProp
because
$.ajax
declaration will override data over
data
from
ajax.preFilter


I want to have both
myProp
and
myItem
parameters to be send to somewhere on server.

Answer

You can use ajaxPrefilter :

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    if (originalOptions.type === 'POST' || options.type === 'POST') {
        options.data = $.extend(originalOptions.data, { myProp : 1});
    }

});
Comments