Select Query with AJAX and PHP

2

I'm developing a system in php and I own a page where it lists multiple results of a SELECT , so far so good ... and I have input text where I would like every letter I typed in it, the results would be filtered according to the letter that I typed, for example: I typed A will appear all results that start with A, if I type a second letter (And for example) after the A, would appear results that were in the beginning of the AE name, of course without having to reload the page. I guess this is done with AJAX, what's the name of it and how can I do it?

    
asked by anonymous 10.09.2016 / 22:38

1 answer

0

Example:

<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str) {
    if (str.length == 0) { 
        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>
</head>
<body>

<p><b>Comece a escrever o nome</b></p>
<form> 
Nome: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Sugestões: <span id="txtHint"></span></p>
</body>
</html>

gethint.php

<?php
// Array com os nomes
$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";

// pega o parâmetro q da URL
$q = $_REQUEST["q"];

$hint = "";

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";
            }
        }
    }
}


echo $hint === "" ? "Sem sugestão" : $hint;
?>

Test Here

I hope it helps.

    
10.09.2016 / 23:12