Observe a descrição do código a seguir.
Código HTML
<!DOCTYPE html>
<html>
<head>
<script>
function sc(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xh = new XMLHttpRequest();
xh.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xh.open("GET", "gethint.php?q="+str, true);
xh.send();
}
}
</script>
</head>
<body>
<p><b>Digite o nome de uma cidade:</b></p>
<form action="">
<label for="fname">Cidade:</label>
<input type="text" id="fname" name="fname" onkeyup="sc(this.value)">
</form>
<p>Sugestão: <span id="txtHint"></span></p>
</body>
</html>
Código PHP
<?php
$c[] = "Santarém";
$c[] = "Belém";
$c[] = "Capanema";
$c[] = "Salvaterra";
$c[] = "Faro";
$c[] = "Goianésia";
$q = $_REQUEST["q"];
$h = "";
if ($q !== "") {
$q = strtolower($q);
$l = strlen($q);
foreach($c as $n) {
if (stristr($q, substr($n, 0, $l))) {
if ($h === "") {
$h = $n;
} else {
$h .= ", $n";
}
}
}
}
echo $h === "" ? "Sem sugestão" : $h;
?>
A descrição do código acima