0

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

1 Answer 1

3

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.