views:

32

answers:

2

I have the following bog standard jQuery ajax request. I've been trying to induce an error state by disconnecting my computer from the network mid-request (the server takes 10 seconds to reply so this is simple).

When I disconnect alert('Success: '+ json); is called, with null for the response json. I would expect the error part to be called.

Anyone know why the disconnect is being treated as a success, and how instead to induce a fail?

$.ajax({
 url : 'post.php',
 data : { id : 123 },
 type: 'POST',
 dataType : 'json',
 success : function(json) {
    alert('Success: '+ json);
 },
 error : function(XMLHttpRequest, textStatus, errorThrown) {
     alert('Error: ' + errorThrown);
 },
 complete : function(xhr, status) { 

 }
});  
+1  A: 
    $.ajax({
     url : 'post.php',
     data : { id : 123 },
     type: 'POST',
     dataType : 'json',
     success : function(json) {
        if(json!=null){
             alert('Success');
        }else{
            exceptionAjax(0,"no server data");
        }
     },
     error : function(XMLHttpRequest, textStatus, errorThrown) {
         exceptionAjax(XMLHttpRequest.statusText,XMLHttpRequest.responseText);
     },
     complete : function(xhr, status) { 

     }
    });

function exceptionAjax(responseStatus,responseText){
      alert('Error');   
}
volkan er
+1  A: 

I think there was/is a bug since the release of jQuery 1.4.

After upgrading from 1.3.2 I noticed that calling an abort on the XMLHttpRequest object triggered the success callback, not the error callback. After poking around the codebase, I noticed that they had replaced the typical abort method with a custom one. Could have something to do with that.

Here's a post about it: http://forum.jquery.com/topic/after-aborting-an-ajax-call-success-event-is-still-being-fired

jarcoal