Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest ReadyState always undefined

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.

like image 784
Abion47 Avatar asked Dec 03 '22 01:12

Abion47


1 Answers

JS 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;
    }
like image 170
Asad Saeeduddin Avatar answered Dec 21 '22 22:12

Asad Saeeduddin