1

Answer is simular to Adding a general parameter to all ajax calls made with jQuery, but I need to add additional param only for ajax calls with method post:

$.ajax({
  url: url,
  type: "POST",
  data: data,
  success: success,
  dataType: dataType
});

May I achieve this without adding param into all ajax calls directly (editing inplace), i.e. via setup param via some sort of common config?

Community
  • 1
  • 1
userlond
  • 3,632
  • 2
  • 36
  • 53

1 Answers1

2

Thanks for comments.

I've also found this post usefull: jQuery's ajaxSetup - I would like to add default data for GET requests only

Solution is (not fully tested yet):

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

P.S. My final solution:

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
    if (options.type.toLowerCase() == 'post') {
        options.data += '&some_dummy_data=lksflkdflksdlkf';
        if (options.data.charAt(0) == '&') {
            options.data = options.data.substr(1);
        }
    }
});

Changes:

  1. options.type contains post in lowercase (just in case I've added toLowerCase)
  2. options.data is string, not object, so I've rewrited query change via plain string manipulation
  3. originalOptions didn't worked, but with options it workes.
Community
  • 1
  • 1
userlond
  • 3,632
  • 2
  • 36
  • 53
  • I don't think you need - `originalOptions.data = $.extend(originalOptions.data, {some_dummy_data: 'lksflkdflksdlkf'});`. $.extend will merge into the target object which is `originalOptions.data`. Also, you don't need `$.extend`. You can simply add `originalOptions.data. = ` unless you are adding more properties to original options – Vigneswaran Marimuthu Dec 11 '15 at 03:11
  • In my case `originalOptions` manipulations didn't help me achieve needed results. And `options.data` is string, not object. I've updated the answer. Thanks for help. – userlond Dec 11 '15 at 04:47