Skin99 Skin99 - 18 days ago 5
HTML Question

Uncaught ReferenceError: xmlhttp is not defined?

<html>
<head>
<title>List</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Javascript code -->
<script>
function showUser(str) {
if (str == " ") {
document.getElementById("txtHint").innerHTML = " ";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<!-- CSS for HTML table -->
<style>
table {
width: 100%;
border-collapse: collapse;
}

table, td, th {
border: 1px solid black;
padding: 5px;
}

th {text-align: left;
}
</style>

</head>
<body>

<form>
<select name="users" onchange="showUser(this.value)">
<option value=" ">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<div id="txtHint">Result from PHP script should appear here</div>
</body>
</html>


When I run the following HTML page in the Google Chrome Browser via Netbeans, I am met with this error (see Title) when I try to select a person from the list.


xmlhttp.onreadystatechange = function()


This line of code and the one below seems to be the areas of concern based on Chrome's Developer tools.


select name="users" onchange="showUser(this.value)


Can anyone pinpoint what needs to be changed?

Answer

Right underneath:

// code for IE7+, Firefox, Chrome, Opera, Safari

Add:

xmlhttp = new XmlHttpRequest();

That way, you'll satisfy web browsers with javascript engines that have XMLHttpRequest defined.

Also, xmlhttp needs to have a valid value (handle) before "xmlhttp.onreadystatechange = function()" can be properly executed.

If your browser (especially very old IE browsers) is still picky then change "xmlhttp" to "var xmlhttp" since var before a variable name means define a new variable.

Comments