add global callback to $.ajaxSetup

ajax, callback, javascript, jquery

Solution

The easiest solution; define your own property for ajax options.

$.ajaxSetup({
    statusCode: {
        403: function(error, callback){
            this.callback403(error);
        }
    }
});

$.ajax({
    callback403: function () {}
});

Note, if you change the `context` option of the ajax request, this may not work.

Problem

I am use `$.ajaxSetup` to use a global authorization method, and global error handling in my site. I would like to pass a callback function into the global error method so I can call the function whenever I need to in the global error handler. Here is my `$.ajaxSetup`: ``` $.ajaxSetup({ global: false, // type: "POST", beforeSend: function (xhr) { //The string needs to be turned into 'this.pasToken' //if not us, don't include if(app.cookieAuth) xhr.setRequestHeader("Authorization", _this.pasToken); }, statusCode: { 401: function(){ //Redirect to the login window if the user is unauthorized window.location.href = app.loginUrl; }, //This is where I need help 403: function(error, callback){ //Show an error message if permission isn't granted callback(error); alert(JSON.parse(error.responseText)['Message']); } } }); ``` Note the `403:` status code. I am trying to pass in a callback function, but I don't know how to do it from the individual `ajax` calls. Anyone have an idea?

Original source