2

What I need is to redirect to a certain url when an error 401 (Unauthorized) response is received. I have several Ajax calls in my code so I am wondering if there is a general way to listen to all of them and only when that code is returned then redirect to that url?

I would like to include this code in all the pages so when received it redirects without having to edit all the AJAX calls in my code.

EDIT: Basically the other answers won't explain the exact mode

It's simply done by doing this:

<script>
    $(document).ajaxComplete(function(response, a){
        if(a.status == 401){
            return window.location.href = '/whatever/url/you/want';
        }
    });
</script>

Thank you in advance

andres.gtz
  • 624
  • 12
  • 22
  • 1
    Possible duplicate of [How to intercept all AJAX requests made by different JS libraries](http://stackoverflow.com/questions/25335648/how-to-intercept-all-ajax-requests-made-by-different-js-libraries) – maaw Apr 25 '17 at 22:20

3 Answers3

6

This answer gave the best answer to your question:

Add a "hook" to all AJAX requests on a page

This code (slightly modded from answer above) illustrates how to intercept the ajax call from the start until finish:

(function() {
    var origOpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function() {
        console.log('request started!');
        this.addEventListener('load', function() {
            console.log('request completed!');
            console.log("Server status code: ", this.status); 
            console.log("Ready state: ", this.readyState); 
            console.log("Server response:", this.responseText);
        });
        origOpen.apply(this, arguments);
    };
})();

What is readyState: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState

JUlinder
  • 995
  • 1
  • 8
  • 19
  • How to use it for ie: if ajax from "yourscripthere.php" is 200 then do something? – Eryk Wróbel Nov 21 '22 at 10:13
  • @ErykWróbel if you're just setting up this script, setup a this.status == 200 && what you want to happend inside the body of the function being called above for .open – JUlinder Nov 21 '22 at 12:22
2

Try this:

$(document).ajaxStart(function () { 
  console.log('Request Initiated'); 
}); 
$(document).ajaxComplete(function () { 
  console.log('Request Complete'); 
});
JUlinder
  • 995
  • 1
  • 8
  • 19
Red Devil
  • 176
  • 1
  • 9
0

To be able to inspect all requests and read, for instance the response status or even the URL requested, you should use ajaxSend:

$( document ).ajaxSend(function( event, request, settings ) {
  console.log("Starting request at " + settings.url);
});

The request object also holds the response status, and settings has the URL.

Reference: https://api.jquery.com/ajaxsend/

Pablo Pazos
  • 3,080
  • 29
  • 42