Esempio PHP AJAX

AJAX viene utilizzato per creare applicazioni più interattive.

Esempio PHP AJAX

Di seguito è un esempio che dimostra come il sito web comunica con il server web quando l'utente digita un carattere nel campo di input:

Esempio

Inserisci le lettere A-Z nel campo di input seguente:

Nome:

Suggerimenti di ricerca:

Spiegazione dell'esempio

Nell'esempio sopra, quando l'utente digita un carattere nel campo di input, viene eseguita la funzione chiamata "showHint()".

Questa funzione viene attivata dall'evento onkeyup.

Di seguito è il codice HTML:

Esempio

<html>
<head>
<script>
function showHint(str) {
    if (str.length == 0) { 
        document.getElementById("txtHint").innerHTML = "";
        return;
    }
        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>Inserisci il nome nel campo di input sottostante:</b></p>
<form> 
Cognome o nome:<input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggerimento:<span id="txtHint"></span></p>
</body>
</html>

Prova tu stesso

Spiegazione del codice:

Prima di tutto, controlla se il campo di input è vuoto (str.length == 0),se lo è, svuota il contenuto del segnaposto txtHint e esci dalla funzione.

Ma, se il campo di input non è vuoto, procedere come segue:

  • Creare un oggetto XMLHttpRequest
  • Creare una funzione che viene eseguita quando il server è pronto a rispondere
  • Inviare una richiesta al file PHP (gethint.php) sul server
  • Attenzione a aggiungere il parametro q a gethint.php
  • La variabile str memorizza il contenuto del campo di input

File PHP - "gethint.php"

Questo file PHP verifica l'array dei nomi e poi restituisce il nome corrispondente al browser:

<?php
// Nome array
 $a[] = "Ava";
 $a[] = "Brielle";
 $a[] = "Caroline";
 $a[] = "Diana";
 $a[] = "Elise";
 $a[] = "Fiona";
 $a[] = "Grace";
 $a[] = "Hannah";
 $a[] = "Ileana";
 $a[] = "Jane";
 $a[] = "Kathryn";
 $a[] = "Laura";
 $a[] = "Millie";
 $a[] = "Nancy";
 $a[] = "Opal";
 $a[] = "Petty";
 $a[] = "Queenie";
 $a[] = "Rose";
 $a[] = "Shirley";
 $a[] = "Tiffany";
 $a[] = "Ursula";
 $a[] = "Victoria";
 $a[] = "Wendy";
 $a[] = "Xenia";
 $a[] = "Yvette";
 $a[] = "Zoe";
 $a[] = "Angell";
 $a[] = "Adele";
 $a[] = "Beatty";
 $a[] = "Carlton";
 $a[] = "Elisabeth";
 $a[] = "Violet";
// Ottieni il parametro q dall'URL
$q = $_REQUEST["q"];
$hint = "";
// Visualizza tutti i hint dell'array, se $q è uguale a ""
if ($q !== "") {
    $q = strtolower($q);
    $len=strlen($q);
    foreach($a as $name) {
        if (stristr($q, substr($name, 0, $len))) {
            if ($hint === "") {
                $hint = $name;
            }
                $hint .= ", $name";
            }
         }
    }
}
// Output "nessuna suggerimento", se non trovato hint o output il valore corretto
  echo $hint === "" ? "nessuna suggerimento" : $hint;
?>
c.html" -->