views:

47

answers:

2

I'm looking for a way to trigger ajax error in success callback. i have tried to explain my problem code below:

$.ajax({
url: requestURL,
data: postData,
type: 'post',
success: function(response){
    if(response.Success){
        // do something
    }else{
        // request workflow fails in this case,
        // i have to trigger this ajax request's error callback
    }
},
error: function(){
    // do something on error case
},
dataType: 'json'
});
+5  A: 
var errorhandler = function(xhr, textStatus, error){
    // do something on error case
};

$.ajax({
   url: requestURL,
   data: postData,
   type: 'post',
   success: function(response){
       if(response.Success){
           // do something
       }else{
           errorhandler();
       }
   },
   error: errorhandler,
   dataType: 'json'
   });
jAndy
Nice, simple, and to the point. :)
Joshua
Make sure you do this though:`errorhandler.apply(this,arguments);` to ensure the scope and arguments are still there (they won't be the same, but they'll be good enough).
balupton
@balupton: in general, I agree. But in this particular case scope doesn't matter. No need to access `this` within the error handler.
jAndy
yes i'm doing this with a way which you suggested, but for example, i have set up global ajax error callback with $.ajaxSetup. and i want to trigger that callback. actually i'm looking way to call this callback error case, over that $.ajax call. But yes this is the simplest solution.
Mehmet Fatih Yıldız
A: 

You could send an appropriate HTTP status code so the error callback is triggered automatically.

The 4xx error range which pertains to client errors might be a good fit. Most API's make use of HTTP statuses to indicate error along with additional JSON/XML data as you're doing. See Twitter's response codes for an example.

Anurag
i can't touch server-side environment and i'm looking for client-side and i'm looking for a way to call inside success case.
Mehmet Fatih Yıldız