Briston12
Briston12

Reputation: 377

Create custom function to extend default jQuery $.ajax

I need to create a function that extends jQuery $.ajax callbacks. In specific, I need to add a default code to every beforeSend(), complete() callback. For instance, I have tried this:

var custom = {};
var tempAjax = function(options,callback){ 
    var defaults = { };
    $.extend(options,defaults);
    return $.ajax(options);
}
custom.ajax = function() {
    if ( !arguments[0].beforeSend ) {
        arguments[0].beforeSend = function() {
            // my default code
        }
    }
    return tempAjax.apply($, arguments).then(function(value) {
        // my default code
    }).fail( function() {
        // my default code
    });
}

it is important that every other $.ajax call will still run the own specific code in addition of the default code I have defined. So the following code:

custom.ajax({
    url:        url,
    data:       data,
    dataType:   type,
    beforeSend: function(result){   
        // other code
    },
    success: function(result){  
        // other code
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) { 
        // other code
    },
    complete: function () { 
        // other code
    }
});

will run // other code and // my default code for each callback type.

I'm not sure my solution is working as expected. Could you help me with that?

edit: it is also important that the default code will be used by custom.ajax and not by standard $.ajax calls that will continue to run normally.

Thanks

Upvotes: 0

Views: 490

Answers (1)

nibnut
nibnut

Reputation: 3127

If the order of execution doesn't matter, then I believe you could use jQuery's global event handlers for your beforeSend, success, error and complete cases.

My understanding is that those will be called for all $.ajax calls afterwards...

Hope this helps!

Upvotes: 3

Related Questions