Ajax call - ready state flow confusion
-
10-10-2019 - |
Question
I was developing using Ajax call and while debugging, I found Ajax is sending request/response so many time than I actually imagined.
Long time ago I got good document describing what's happening behind the scene but I lost it.
Nowadays Ajax tutorials on the web only talks about how to code and those IF statement only checks readystate == 4
and status == 200
which does not provide good explanation for someone like me.
I tested the flow with code below and output is I think weird. My confusion is why ready 4 state is showing up twice? According to the definition, ready 4 means completed so there should be no reason to complete twice?
OUTPUT
START
ready 1 //loading
START
ready 2 //loaded
ready 2 status=200 //loaded
START
ready 3 //interactive
ready 3 status=200 //interactive
START
ready 4 //complete
START
ready 4 //complete ... again???
TEST CODE snippet
xmlHttp.onreadystatechange = function() {
alert("START");
if(xmlHttp.readyState == 0) {
alert('ready 0');
alert('ready 0 status=' + xmlHttp.status);
}
if(xmlHttp.readyState == 1) {
alert('ready 1');
alert('ready 1 status=' + xmlHttp.status);
}
if(xmlHttp.readyState == 2) {
alert('ready 2');
alert('ready 2 status=' + xmlHttp.status);
}
if(xmlHttp.readyState == 3) {
alert('ready 3');
alert('ready 3 status=' + xmlHttp.status);
}
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
alert('ready 4');
}
}
Solution
You can read in quirksmode about the way different browsers behave with AJAX calls and readyState.
I found this link that claims using the Abort
command will issue a readystate 4 (have not tested it) - are you using Abort
?