10

In web programming (JavaScript, Dart, etc), how can I tell if my XMLHttpRequest (aka AJAX) request failed because of a network error?

I define network error as anything like DNS, TCP, connection issues, etc.

Thanks!

Seth Ladd
  • 112,095
  • 66
  • 196
  • 279
  • Have a Look - http://stackoverflow.com/questions/1730692/jquery-ajax-how-to-detect-network-connection-error-when-making-ajax-call – Ankit Jan 20 '14 at 18:45
  • The timeout doesn't always work. I tested locally with my server turned off, and the XHR request failed instantly. In some cases, timeout probably works as one indicator. – Seth Ladd Jan 20 '14 at 19:03

3 Answers3

8

In Dartium, and in Chrome JS at least, you can detect the failure by seeing that you hit readyState == 4 ("done") with a status of zero. Zero is not a valid server response, all HTTP server responses are above 100, so it means that it didn't actually reach the server (or at least the server didn't speak proper HTTP).

The onError stream will also get a progress event at this point.

In synchronous mode, the error will be thrown instead.

lrn
  • 64,680
  • 7
  • 105
  • 121
-1

Usually the answer of the AJAX calls come with a status code, and a responseText properties, if you have access to the data that comes from the call, try to read data.status and data.responseText and see if you get them correctly (200 is for success, 500 is for internal server error, etc).

taxicala
  • 21,408
  • 7
  • 37
  • 66
  • 2
    So what are the values for status and responseText that indicate the request never made it to the server due to some network issue? – Seth Ladd Jan 20 '14 at 21:44
-2

u need to check, what response code is returned from in response, if that code is returning 500, means there is a server issue.

Ashish Ratan
  • 2,838
  • 1
  • 24
  • 50
  • 5
    A 500 also means there was a server error (e.g. bad database driver caused an exception). So I can't rely on 500 to always mean a network issue. – Seth Ladd Jan 20 '14 at 19:02