11

I'm currently rewriting all my ajax calls to use the jquery method (much cleaner code! ) and have declared a default ajaxError function, shown below:

$(document).ajaxError(function(event, request, settings){
  alert("there was some error.. boo");
});

My ajax call with its own defined error function that I don't want the default above to fire for:

$.ajax({ url: url,
    success: function(data){
        // do something
    },
    error: function (r, textStatus, errorThrown) { 
        // let's do something here regarding the error
        alert("Oh no! Something went terribly wrong in here!");
        // just trying this to see if it will stop any other events (ie default ajaxError)
        event.stopImmediatePropagation();
    }
});

However, now I have a few ajax calls where I want to declare an error function in the ajax call. I was hoping that by declaring an error function in the ajax call, it would replace the default error call I have defined. But that does not appear to be the case, as I continue to first get my ajax function error call, then I also see the above code execute.

I tried calling event.stopImmediatePropagation() from within my ajax error function hoping that it would stop further events firing (ie: the default error event) but that didn't do anything except tell me in firefox that "event" was undefined.

Any ideas? I was hoping I wouldn't have to go through and define an error function to EVERY ajax call. If it comes down to that, I will. Just figured I'd ask.

Thanks, Matt

1 Answer 1

9

There's a global option on $.ajax() for this that determines whether or not to execute those global AJAX event handlers, just set it to false, like this:

$.ajax({ 
    url: url,
    global: false,
    success: function(data){
        // do something
    },
    error: function (r, textStatus, errorThrown) { 
        alert("Oh no! Something went terribly wrong in here!");
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

What if I only want to override the error function? I want to retain any other global functions that might be set (eg ajaxSend, ajaxComplete)?
@John - Just leave off the functions you don't want to override and the globals will be used :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.