Select Query with AJAX and PHP

Asked

Viewed 102 times

2

I am developing a php system and have a page where it lists several results of a SELECT, so far so good... and I have a input text where I would like every letter I typed into it, the results to be filtered according to the letter I typed, for example: I typed A will show all results starting with A, if I type a second letter (And for example) After A, results would appear that there were at the beginning of the AE name, of course without having to reload the page. I imagine this is done with AJAX, what is the name of it and how can I do it?

  • has the titter typeahead that does just that. But if you search for live search you also find enough thing on the subject

  • Thank you very much.... I’m still beginner in development... I’m turning around, which would you recommend for me ? I just need it even without many other things, the basics of that same function..

  • I would go with the same twitter, already in the market for a long time, it is not very complicated and is relatively flighty.

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.