When should XMLHttpRequest's onerror handler fire When should XMLHttpRequest's onerror handler fire javascript javascript

When should XMLHttpRequest's onerror handler fire


As mentioned in the comments, onerror fires when there is a failure on the network level. If the error only exists on the application level, e.g., an HTTP error code is sent, then onload still fires. You need to test the returned status code explicitly in your onreadystatechange handler.

Note that a denied cross-domain request will also fire the onerror handler.


In addition to apsillers' answer, note that XMLHttpRequest handles redirects automatically in the background, so you don't have to check for this reply codes in the onload event (this event will be invoked only once - on the final call). Also note, that in case you send payload data with the POST method and if the requests is redirected, XMLHttpRequest change the method from POST to GET and discards any payload data for security reasons. The onload event will still be invoked but you will need to re-send your request manually again to the new destination.