Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 392
Saif Bechan Avatar asked Dec 02 '11 23:12

Saif Bechan


2 Answers

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
    }
});
like image 132
Bojangles Avatar answered Oct 12 '22 09:10

Bojangles


Another variation to Bojangles answer is that you can pass additional arguments like this so that you have more control over the request.

Since this code would run on every single request, so if you want to trigger a Click function you probably don't want to trigger it every now and then for every request. So you would wrap your click code inside some conditional IF statement.

$(document).ajaxComplete(function(event,request, settings){
    // Your code here
});
like image 3
Faisal Ashfaq Avatar answered Oct 12 '22 09:10

Faisal Ashfaq