Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

Reputation: 67131

$.ajax combining with $.ajaxSetup default settings

I have a way of keeping track of current Ajax Requests which involves $.ajaxSetup(), and counting beforeSends & completes.

jsFiddle Demo

var ajaxProcs = 0;

$.ajaxSetup({
    beforeSend : function () { ajaxProcs++; },
    complete   : function () { ajaxProcs--; }
});

The problem is, if any given $.ajax() call has beforeSend or complete it will throw off the correct count of Ajax requests running.

For example, this would overwrite it, and not add 1 to the ajaxProcs count.

$.ajax({
    beforeSend : function () { /* blah blah */ }
});

Is it possible to have BOTH ajaxSetup AND the $.ajax Override run?

Upvotes: 1

Views: 5175

Answers (4)

GianFS
GianFS

Reputation: 2615

How about this, let's try beforeSend() function as a sample..

$.ajaxSetup({
    beforeSend: function(){
        console.log('execute another beforeSend() function'); 
    }
});

Then this is your Ajax function:

$.ajax({
    beforeSend : function () { 
        console.log('execute beforeSend() function');
        if('beforeSend' in $.ajaxSettings){
            $.ajaxSettings.beforeSend();
        }
    }
...

And now it will execute the both functions

Hope it helps

Upvotes: 4

BenjaminCorey
BenjaminCorey

Reputation: 411

Try this:

var ajaxProcs = 0;
$(document).ajaxSend(function(){
  ajaxProcs++;
});
$(document).ajaxComplete(function(){
  ajaxProcs--;
});

This will run on every jQuery ajax call, regardless of what callbacks you bind to the individual requests.

Upvotes: 3

nanobar
nanobar

Reputation: 66405

Because of how jQuery is designed I think your best bet is to make a rule to call the ajaxSetup function manually from the beforeSend. Even if jQuery had a more OO approach you would still have to call the parent anyway - it won't magically call itself.

http://jsfiddle.net/mrcJ7/

var ajaxProcs = 0;

var setupObj = {
    beforeSend : function(xhr) { ajaxProcs++; console.log('Increased to: ' + ajaxProcs); },
    complete   : function() { ajaxProcs--; console.log('Decreased to: ' + ajaxProcs); }
};

$.ajaxSetup(setupObj);

$.ajax({
    url: 'http://fiddle.jshell.net',
    beforeSend : function (xhr) { 
        setupObj.beforeSend(xhr);
    }
});

Upvotes: 1

Lee Meador
Lee Meador

Reputation: 12985

ajaxSetup() provides default values for parameters that can be passed to the ajax() function. They only apply as defaults and not when supplied in the actual ajax() call.

JQuery's ajaxStart(), ajaxSend() and ajaxComplete() are things you might want to read about. They are called before and after each ajax call.

There is a global option on the individual ajax() call that will disable those global functions though.

Not really a complete answer because it is overridable but maybe helpful.

Upvotes: 2

Related Questions