userlond
userlond

Reputation: 3818

Add a parameter to all ajax calls with method POST made with jQuery

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?

Upvotes: 1

Views: 2445

Answers (1)

userlond
userlond

Reputation: 3818

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.

Upvotes: 2

Related Questions