Qpirate
Qpirate

Reputation: 2078

Override Ajax Success event

I am trying to override the jQuery ajax function to handle a default action on a success event but also executing the callback function that i am using in the options parameter. What the purpose is there is tags returning in the response that I always want to strip out of the response for use elsewhere.

The scenario is:

Can anyone help? I have tried extending

The code I have is:

var _ajaxSuccess = jQuery.fn.ajaxSuccess;  
$.fn.extend({  
    ajaxSuccess: function (a)  
    {  
        _ajaxSuccess.apply(this, a);  
    }  
});

Upvotes: 2

Views: 9737

Answers (3)

seymar
seymar

Reputation: 4063

Do like this:

$.ajaxSuccess(function(){
    //somethingtodo
});

Mentioned in http://tutorialzine.com/2011/06/15-powerful-jquery-tips-and-tricks-for-developers/ heading twelve.

Upvotes: 0

mu is too short
mu is too short

Reputation: 434665

There is the global ajaxSuccess callback:

Whenever an Ajax request completes successfully, jQuery triggers the ajaxSuccess event. Any and all handlers that have been registered with the .ajaxSuccess() method are executed at this time.

That will let you call your own function on every successful AJAX call without interfering with the usual success callbacks.

There are various other global AJAX event handlers that you might want to look at too.

If those callbacks don't have the right timing or capabilities for you, then you could write your own wrapper for $.ajax and use that:

function wrapped_ajax(options) {
    var success = options.success;
    options.success = function(data, textStatus, jqXHR) {
        // Do whatever needs to be done here.
        if(success)
            success(data, textStatus, jqXHR);
    };
    return $.ajax(options);
}

You can do whatever you need to the usual success callback parameters before calling the original success callback. You'd call wrapped_ajax in exactly the same way as $.ajax. You could use the same technique to hook into the other callbacks as well.

Upvotes: 6

Amir Ismail
Amir Ismail

Reputation: 3883

try jQuery.ajaxSetup it may help you ,read about it here

Upvotes: 2

Related Questions