Inator
Inator

Reputation: 1024

jQuery exceptions to global $.ajaxSetup() possible?

I use the following to catch an unauthorized access and force a login:

$.ajaxSetup({
    statusCode: {
        401: function(){
            //do stuff
        }
    }
});

Works great... when accessing resources on my servers (domain), but now I'm attempting to use 3rd party API resources via ajax calls and their 401's are caught by this as well. So, how might I either:

  1. rewrite the above code to only catch 401's from my domain, or
  2. make an $.ajax() call with an exception to the above code (use a different error handler)

Thanks much!

Upvotes: 12

Views: 5469

Answers (3)

gen_Eric
gen_Eric

Reputation: 227280

Expanding on @MrOBrian's answer, in your 401 function, this is set to a settings object containing info about the AJAX request. One of the properties is url. You can read this, and check if it's your URL or not.

$.ajaxSetup({
    statusCode: {
        401: function(){
            var url = this.url;
            if(url === myurl){ // check if url is yours
            }
            else{
                // not your URL, do nothing
                return;
            }
        }
    }
});

Upvotes: 1

Inator
Inator

Reputation: 1024

Through experimentation I discovered the answer. $.ajaxSetup() basically sets a default for any $.ajax() requests. However, the global setup can be overridden for a specific request like so:

$.ajaxSetup({
    statusCode: {
        401: function(){
            //this will catch any and all access denied errors
        }
    }
});

$.ajax({
    type: 'GET',
    dataType: 'json',
    url: someresouceurl,
    statusCode: {
        401: function(){
            //except this one!
        }
    },
    success: function(data) {
    }
});

Upvotes: 14

MrOBrian
MrOBrian

Reputation: 2189

From the jQuery API

If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error, they take the same parameters as the error callback.

I would recommend looking into the jqXHR parameter you get and see if you can narrow it down to just your domain, but I don't know enough about that aspect of jQuery to give you exact code.

Upvotes: 0

Related Questions