Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .ajaxError AND setting an error function in $.ajax()

Tags:

jquery

ajax

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

like image 591
Matt Avatar asked Jun 25 '10 20:06

Matt


1 Answers

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!");
    }
});
like image 160
Nick Craver Avatar answered Oct 20 '22 12:10

Nick Craver