Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle 403 ajax response in jQuery

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?

like image 554
Gasim Avatar asked Aug 04 '13 10:08

Gasim


2 Answers

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
}
like image 177
Gasim Avatar answered Oct 14 '22 05:10

Gasim


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);
like image 33
Dario Zadro Avatar answered Oct 14 '22 06:10

Dario Zadro