Saif Bechan Saif Bechan - 5 months ago 15
jQuery Question

Listen for ajax POST responses with jQuery

I am working on a project that does some ajax actions. Now the ajax calls are done by scripts, and I do not want to get into those scripts.

Further, the responses that are sent back are very random and not that easy to grab hold of. They do not have a solid class where I can look for.

The best option for me would be that whenever a post is returned by whatever function on the page, one of my functions is fired. Note that I do not know from where the calls are made, and I am not interested in that. The only thing I want to know is if there is a post received. I am also not interested in the actual post reponse data. Just want to fire a function whenever the page receives some response from a POST made by the page.

Is something like that possible.

Answer

Take a look at .ajaxSetup(). It allows you to add code that is executed for any AJAX event triggered from anywhere in your JS code.

To run something on the success: event, this will do the trick:

$.ajaxSetup({
    success: function() {
        // Your code
    }
});

To catch any AJAX event, failed or not, use this:

$.ajaxSetup({
    ajaxComplete: function() {
        // Your code
    }
});