nap
nap

Reputation: 11

Unable to detect 403 status code in jquery AJAX call

I am using the following code to invoke an application on another users machine on port 9084 (for the lack of a DEV server). This is a JAVA application that I would like to call from my ASP.Net application (it uses master pages). I would like to call the URL below which will return a 403 error status and a session ID in a cookie. I would like to use this session ID and make another call using an application ID and password.

When I use the URL "http:fwdslash fwdslash machinename:9084 fwdslash PropertyInsuranceDB fwdslash propertyAssociation fwdslash ajax fwdslash getPolicyAddress fwdslash H0271812 fwdslash 08" in the browser, I get the HTTP 403 Forbidden error page. When I try the code as below, I see the same in Fiddler, but I am not able to trap it in the error section of the ajax call below.

What could I be doing wrong? Any suggestions will be greatly appreciated.

$.ajax({   url: "http://machinename:9084/PropertyInsuranceDB/propertyAssociation/ajax/getPolicyAddress/H0271812/08",
            context : document.body,
            type: "get",
            success: function (data, status) {
                alert(status);
            },
            error: function (xhr, desc, err) {
                alert(xhr.status);
                alert(desc);
                alert(err);
            }
        });

Thanks

--Nivedita

Upvotes: 1

Views: 4628

Answers (2)

le0diaz
le0diaz

Reputation: 2508

If you want to do it globally, jquery gives and API for it (docs here). Some people suggest changing the default configuration with ajaxSetup, but jquery discourages it. So the preferred method is like this one:

$( document ).ajaxComplete(function( event, xhr, settings ) {

        if(xhr.status == 403){//unauthorized calls
            // do whatever want with the event ie:
            //event.stopImmediatePropagation();
            //show a global UI for ajax login again
            console.error('403 response');
        }

});

Upvotes: 2

adeneo
adeneo

Reputation: 318342

If the server returns something, it's usually considered a successful ajax call, even if it doesn't return what you want it to return.

To catch the status codes you can do

    $.ajax({
     url: "YOURURLHERE",
     context: document.body,
     type: "get",
     statusCode: {
         403: function (xhr) {
             console.log('403 response');
         }
     },
     success: function (data, status) {
         alert(status);
     },
     error: function (xhr, desc, err) {
         alert(xhr.status);
         alert(desc);
         alert(err);
     }
 });

Upvotes: 6

Related Questions