Listen to ajax POST answers with jQuery

I am working on a project that performs some ajax activities. Now ajax calls are made by scripts, and I don't want to go into these scripts.

In addition, responses that are sent back are very random and not so easy to grab. They do not have a solid class where I can search.

The best option for me would be that whenever a message is returned by any function on the page, one of my functions starts. Please note that I do not know where the calls were made from , and I am not interested in this. The only thing I want to know is if there is a message. I am also not interested in the actual response data . You just need to run the function when the page receives a response from the POST made by the page.

It is possible.

+4
source share
2 answers

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

To fire something in 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 } }); 
+8
source

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

Since this code will be run for each individual request, therefore, if you want to call the Click function, you probably do not want to run it every time and every time for every request. That way you would wrap your click code inside some conditional IF statement.

 $(document).ajaxComplete(function(event,request, settings){ // Your code here }); 
0
source

Source: https://habr.com/ru/post/1384423/


All Articles