I set up the usual XMLHttpRequest and everything works fine so far, I can retrieve data and readyState changes and does all sorts of things.
One thing that doesn't happen though is that readyState ever triggers the onreadystatechange() function when it reaches 0.
Now I'm wondering... why?
I looked into the XMLHttpRequest MDN entry but there's no mention of why onreadystatechange should NOT fire when readyState reaches 0. I also found no other information on the topic...
Snippet:
// Inside a class, this = class instance
this.socket = new XMLHttpRequest();
// For easy access of this class instance in onreadystatechange
var client = this;
// Write current readyState to console
this.socket.onreadystatechange = function ()
{
// Adding this just to verify there are no errors in if block
console.log("readyState: "+client.socket.readyState);
if(client.socket.readyState === 0)
{
console.log("readyState is 0");
}
else
{
console.log("readyState is "+client.socket.readyState);
}
}
When the XMLHttpRequest socket is done processing the request, the XMLHttpRequest instance will have the value readyState===0, at least Firefox' JS console tells me that.
After doing a request, the JS console lists the log messages for readyStates 1-4 correctly, but no message for readyState 0, not before the request and not afterwards.
In theory, when the readyState changes from 4 back to 0, shouldn't the onreadystatechange() function be triggered? Checked this on macOS with current FF and Safari, as well as on Win with IE11, the same behaviour everywhere, onreadystatechange() never fires for readyState 0.
Is XMLHttpRequest intentionally not doing that, by design, or am I doing something wrong? Grateful for any helpful input. :)
(Please no "use jQuery" comments or similar, thx.)
UPDATE:
Turns out the readyState stays at 4 forever after a successful or failed request is completed, verified in FF, IE, Safari.
However, the readyState will return from > 0 to 0 if an ongoing request is aborted. So a readystatechange does happen, but the onreadystatechange is not fired, verified this in FF and Safari.
UPDATE 3:
According to the XMLHttpRequest spec, when XHR is in readyState 3 (receiving) and aborted, the XHR should set readyState to 4 (done) with an onreadystatechange event, issue a network error and then set readyState to 0 (unsent) with no onreadystatechange event.
But when I abort an XHR that is in readyState 3 (receiving), it will first set readyState to 4 (done) with an onreadystatechange event and HTTP status 200 (OK), then it will trigger onabort and onloadend and reset readyState to 0 (unsent) ... but at no point is an onerror Event triggered.
Very confusing.