1

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.

Snake Eyes
  • 16,287
  • 34
  • 113
  • 221
  • http://stackoverflow.com/questions/16980840/how-can-i-set-ajaxstart-and-ajaxstop-to-fire-only-on-post-requests – Umesh Sehta Jul 20 '15 at 10:23
  • possible duplicate of [jQuery's ajaxSetup - I would like to add default data for GET requests only](http://stackoverflow.com/questions/6996993/jquerys-ajaxsetup-i-would-like-to-add-default-data-for-get-requests-only) – George Jul 20 '15 at 10:23
  • It is no duplicate. I will explain above in my edited question. – Snake Eyes Jul 20 '15 at 10:48

1 Answers1

2

You can use ajaxPrefilter :

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

});
Mark
  • 6,731
  • 1
  • 40
  • 38
Royi Namir
  • 144,742
  • 138
  • 468
  • 792