<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} 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>
</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>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>
The page shows the dropdown list. However, it seems the onchange method is not triggered. I don't get any return from the php. The php code is here. https://www.w3schools.com/php/php_ajax_database.asp
</div>
It seems to be working for me. Are you running this html file off your local machine? What I mean is that when you are loading this html file on your browser, does the address bar read file://<path_to_html>
or http(s)://<path_to_html>
?
If it is the former, then you need to provide the full path to the server that's hosting the getuser.php
.
When I tried your code (running the html off my local machine), the onchange
event was being triggered and the xmlhttp
object was being created but no http request was being sent to the server (as per what I saw on by browser's dev tools). Then I realized I had to change the location of the getuser.php
because it needed to be hosted on a server.
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return; /* i think this is not correct you have to return something*/
}
xmlhttp = new XMLHttpRequest();
/* i pretty sure that xmlhttp should be a variable */
var xmlhttp = new XMLHttpRequest();
/* this could be one of the major error. Also try using chrome dev tools and debug using console if problem still persists */
Also make sure you have turned on the virtual server like Apache. You need a server to run php files!