ashkufaraz
ashkufaraz

Reputation: 5297

Send parameter to ajax start function

I have a jQuery ajax request as:

$.ajax({
    type: "POST",
    url: "calculate.php",
    data: {},
    dataType: 'json',
    success: function (response) {
    }, error: function (jqXHR, textStatus, errorThrown) {

    }
});

Before the ajax starts, I want to send a parameter to function ajaxStart like below

$(document).ajaxStart(function (xxx) {
  alert("parameter equals to="+xxx);
});

How can I send parameter xxx to ajaxStart when my request is started? Is it possible to send parameter to ajaxStart?

Upvotes: 2

Views: 750

Answers (1)

adeneo
adeneo

Reputation: 318222

You could use $.ajaxSetup or $.ajaxSend to change the data sent in the request before the request happens. Something like

$(document).ajaxSend(function( event, jqxhr, settings ) {
    settings.data = settings.data + '&param=value'
});

A more extendable approach would be to use $.param and check that there is data before extending it

$(document).ajaxSend(function( event, jqxhr, settings ) {
  var params = {param : 'test'};
  var sep    = settings.data && settings.data.length ? '&' : '';

  settings.data = settings.data + sep + $.param(params);
});

Upvotes: 3

Related Questions