Gasim
Gasim

Reputation: 7991

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?

Upvotes: 8

Views: 17152

Answers (4)

PetitCitron
PetitCitron

Reputation: 41

$.post('/foo/', {data : example})
   .done(function (data) {
        // success code
    })
   .fail(function(res) {
       if (res.status === 401 || res.status === 403) {
           // failed code
           alert('Forbidden')
        }
   });

Upvotes: 0

Dario Zadro
Dario Zadro

Reputation: 1284

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);

Upvotes: 3

Gasim
Gasim

Reputation: 7991

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
}

Upvotes: 12

Swadeesh
Swadeesh

Reputation: 576

Check if the URL provided is correct.

If 403 is still received as response, try to use try - catch block and handle error accordingly.

try
  {
  //Run some code here
  }
catch(err)
  {
  //Handle errors here
  }

Upvotes: -1

Related Questions