How to handle 403 ajax response in jQuery

13,320

Solution 1

Solution: The best I found to deal with this situation per ajax request is to use statusCode method:

statusCode: {
   403: function() { 

   },
   200: function(data) {

   }
   //other codes. read the docs for more details
}

Solution 2

This works great for all my apps:

(function($){
    $(document).on('ajaxError', function(event, xhr) {
      if (xhr.status === 401 || xhr.status === 403) {
        window.location.reload();
      }
    });
})(jQuery);
Share:
13,320

Related videos on Youtube

Gasim
Author by

Gasim

Updated on June 04, 2022

Comments

  • Gasim
    Gasim over 1 year

    I need help handling 403 errors that come from my server in $.ajax request of jquery. It sends it as JS error because the request is forbidden but I just want the error to be a part of Ajax response, not just a JS error that fails the entire application. The 403 comes from OAuth2. If any code needs to be provided to clarify my question better, please let me know.

    How can I achieve that?

  • Gasim
    Gasim over 10 years
    The url provided is correct but the request is HTTPS if that makes a difference. I am using $.ajax request of jquery which in the source code says "Do not use try/catch. jquery handles it itself" (something like that). I am going to try to find some other way to get around it. Thanks.
  • thdoan
    thdoan over 7 years
    If a server is sending 403 in a response, then the server is misconfigured because per RFC spec a 403 is when the server should NOT fulfill the request, meaning it should not send a response.
  • thdoan
    thdoan over 7 years
    If a server is configured properly, using statusCode will not help you handle 403 errors (see my comment below). Try it out yourself by trying to $.getJSON() this file (it should return a proper 403 - Access Denied).
  • Matthew
    Matthew over 6 years
    I disagree with @10basetom. Docs say not to drop the response. The response "SHOULD" be fulfilled with either 404 if you don't want to reveal the existence of the resource, or 403 if you do.
  • AaA
    AaA over 1 year
    @thdoan, that url doesn't even return response, which means I cannot verify the properly configured. that is also why link only answers are bad