I'm following the PHP/AJAX tutorials at w3schools, and I've hit a bit of a roadblock at square one. Every time I call this function, the readystate is always undefined.
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
var xmlhttp;
if (window.XMLHttpRequest) {
console.log("Using XMLHttpRequest");
xmlhttp = new XMLHttpRequest();
}
else {
console.log("Using ActiveXObject");
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
console.log(xmlhttp.readystate);
if (xmlhttp.readystate == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.status);
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
}
If I change this line:
if (xmlhttp.readystate == 4 && xmlhttp.status == 200) { ...
to this (via typo):
if (xmlhttp.readystate = 4 && xmlhttp.status == 200) { ...
Then it works, but it feels kind of like a "magic happens here" thing to be writing the code like this.
I'm following the PHP/AJAX tutorials at w3schools, and I've hit a bit of a roadblock at square one. Every time I call this function, the readystate is always undefined.
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
var xmlhttp;
if (window.XMLHttpRequest) {
console.log("Using XMLHttpRequest");
xmlhttp = new XMLHttpRequest();
}
else {
console.log("Using ActiveXObject");
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
console.log(xmlhttp.readystate);
if (xmlhttp.readystate == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.status);
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
}
If I change this line:
if (xmlhttp.readystate == 4 && xmlhttp.status == 200) { ...
to this (via typo):
if (xmlhttp.readystate = 4 && xmlhttp.status == 200) { ...
Then it works, but it feels kind of like a "magic happens here" thing to be writing the code like this.
Share Improve this question asked Nov 29, 2012 at 23:22 Abion47Abion47 24.7k6 gold badges74 silver badges97 bronze badges 1 |1 Answer
Reset to default 18JS is case sensitive. You need to check the readyState
property, not the readystate
property.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.status);
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
xmlhttp.readystate = 4
(with single equals sign, assignment) assigns4
to the.readystate
property and is an expression that evaluates to4
, which is atruthy
value and thus passes the if check. So it might as well have beenif( true && xmlhttp.status == 200 )
or justif( xmlhttp.status == 200)
– Esailija Commented Nov 29, 2012 at 23:39