Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery exceptions to global $.ajaxSetup() possible?

Tags:

jquery

ajax

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!

like image 642
Inator Avatar asked Jul 11 '12 20:07

Inator


People also ask

When a jQuery AJAX operation fails the global event can be invoked?

version added: 1.0.Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event. Any and all handlers that have been registered with the . ajaxError() method are executed at this time.

What is ajaxSetup?

Definition and Usage. The ajaxSetup() method sets default values for future AJAX requests.

What is global in AJAX?

Category: Global Ajax Event HandlersThese methods register handlers to be called when certain events, such as initialization or completion, take place for any Ajax request on the page. The global events are fired on each Ajax request if the global property in jQuery. ajaxSetup() is true , which it is by default.

How does AJAX return an API call?

ajax returns immediately and the next statement, return result; , is executed before the function you passed as success callback was even called.


1 Answers

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) {
    }
});
like image 109
Inator Avatar answered Oct 20 '22 03:10

Inator