as far as XMLHttpRequest() Object is concerned, it is fine, the problem is with onreadystatechange for example if I put my code this way, it works perfect.<
try using
xmlHttp.onreadystatechange = handleServerResponse;
Note the removed paranthesis.
I know that this is kind of old, but I just spent a couple of hours trying to make a similar program work in Chrome.
The only way that I could make it work was to use the this
object.
Using a global xmlHttp
instead of this
results in the handleServerResponse()
to be called only once when xmlHttp.readyState == 2
.
Here is the code that works in Google Chrome Version 81.0.4044.129 (Official Build) (32-bit).
handleServerResponse()
gets called 4 times, each time xmlHttp.readyState
gets incremented.
Found by using Developer Tools in Chrome and monitoring the this
object, amongst others.
function process(){
var xmlHttp = new XMLHttpRequest();
if(xmlHttp){
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.open("GET", "hello.txt", true);
xmlHttp.send();
}
}
function handleServerResponse(){
theD = document.getElementById("theD");
if(this.readyState == 1){
theD.innerHTML += "Status 1: Server connection established ! <br/>";
}
else if(this.readyState == 2){
theD.innerHTML += "Status 2: Request recieved ! <br/>";
}
else if(this.readyState == 3){
theD.innerHTML += "Status 3: Processing Request ! <br/>";
}
else if(this.readyState == 4){
if(this.status == 200){
var text = this.responseText;
theD.innerHTML += "Status 4: Processing Request ! <br/>";
theD.innerHTML += text;
}
else{
alert("Something is wrong !");
}
}
}
use this xmlHttp.onreadystatechange = handleServerResponse
then write as function handleServerResponse(xmlHttp) it will work
Two things:
xmlHttp.open("GET", "hello.txt", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send();
As you see, I removed the parentheses and I inverted the order of open
and onreadystatechange
.
The first thing, is because otherwise you do not associate the function reference itself, but the function's return value – because, basically, you're executing it. It's the same difference to have:
var a = sum(1, 2); // 3, assign to `a` the return value of `sum`
var b = sum; // assign to `b` the `sum` function ref.
var c = b(1, 2); // 3, therefore `b` is an 'alias' to `sum`
The second thing, it depends by the browser: for instance, some version of IE "reset" the onreadystatechange
of a XMLHttpRequest
instance, every time the open
method is called. So if you set the onreadystatechange
before the open
, that works as "initializator", there is a chance, depends by the browser, that would be removed – and therefore never called – once the open
method is called.
So to be fully compatible, it's better set the onreadystatechange
after the open
method – but of course before the send
.