I am learning web dev, I am stuck at calling PHP from a javascript file. I would really appreciate pointers on where I have gone wrong in the example below. When I run it, the HTML part works but it doesn’t reach the PHP and receive data from it. I’ve tested PHP by running another file directly in the browser, it works fine. All the other services on XAMPP are running. Both the js and php files are located in the same folder, using Windows if it helps.
I have also stepped through the code, it is stopping at this line below in the js file
var xmlhttp = new XMLHttpRequest();
It’s not running past that point
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Suggest</title>
</head>
<script>
function showHint(str) {
if(str.length == 0){
//print(str);
document.getElementById("txtHint").innerHTML = "";
return;
}else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200){
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "gethint.php?q" + str, true);
xmlhttp.send();
}
}
</script>
<body>
<b> Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
gethint.php
<?php
/**
* Created by PhpStorm.
* User: dkamt
* Date: 13/02/2019
* Time: 23:39
*/
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
$a[] = "Hege";
$a[] = "Inga";
$a[] = "Johanna";
$a[] = "Kitty";
$a[] = "Linda";
$a[] = "Nina";
$a[] = "Ophelia";
$a[] = "Petunia";
$a[] = "Amanda";
$a[] = "Raquel";
$a[] = "Cindy";
$a[] = "Doris";
$a[] = "Eve";
$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>