"using ajax to get data from a php array" Code Answer

3

based on your reference link i have written this answer, use same html and javascript just replace the php with

<html>
<head>
<script>
function showhint(str) {
    if (str.length == 0) { 
        document.getelementbyid("txthint").innerhtml = "";
        return;
    } else {
        var xmlhttp = new xmlhttprequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readystate == 4 && xmlhttp.status == 200) {
                document.getelementbyid("txthint").innerhtml = xmlhttp.responsetext;
            }
        };
        xmlhttp.open("get", "get_hint.php?q=" + str, true);
        xmlhttp.send();
    }
}
</script>
</head>
<body>

<p><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>

<?php
// 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 = array_search($name, $a);
            } else {
                $hint .= ", " . array_search($name, $a);
            }
        }
    }
}

// output "no suggestion" if no hint was found or output correct values 
echo $hint === "" ? "no suggestion" : $hint;
?>

output

and for your case.

<?php
// array with names
$a = array(
"sarah" => 1,
"sam" => 12,
"tim" => 2,
"tom" => 13,
 );
// 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 $key=>$name) {
        if (stristr($q, substr($key, 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;
?>

output

By Sebi on June 2 2022

Answers related to “using ajax to get data from a php array”

Only authorized users can answer the Search term. Please sign in first, or register a free account.