Solució exercici6-ajax

De wikiserver
Dreceres ràpides: navegació, cerca

//fitxer html

<!DOCTYPE html>
<html lang="ca">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exercici 6 AJAX</title>
</head>

<body>
    <h1>Exercici 6 AJAX</h1>
    <input type="text" id="input"></input>
    <br>Suggeriments:
    <div id="contingut"></div>

    <script lang="javascript">
        var xhr = new XMLHttpRequest();

        var contingut = document.getElementById("contingut");
        var input = document.getElementById("input");

        input.oninput = function () {
            xhr.open("GET", "ex6.php?q=" + input.value);
            xhr.send(null);
        };

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                contingut.innerHTML = xhr.responseText;
            }
        };
    </script>
</body>

</html>

//fitxer php

<?php
// Array with names
$a = array("Anna", "Brittany", "Cinderella", "Diana", "Eva", "Fiona", "Gunda", "Hege", "Inga", "Johanna", "Kitty", "Linda", "Nina", "Ophelia", "Petunia", "Amanda", "Raquel", "Cindy", "Doris", "Eve", "Evita", "Sunniva", "Tove", "Unni", "Violet", "Liza", "Elizabeth", "Ellen", "Wenche", "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 .= "<br>$name";
            }
        }
    }
}

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