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);
Related videos on Youtube
Author by
Gasim
Updated on June 04, 2022Comments
-
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 over 10 yearsThe 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 over 7 yearsIf 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 over 7 yearsIf 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 over 6 yearsI 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 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