Esempio PHP AJAX
AJAX viene utilizzato per creare applicazioni più interattive.
Esempio PHP AJAX
L'esempio seguente mostra come una pagina Web può comunicare con un server Web mentre un utente digita i caratteri in un campo di input:
Esempio
Start typing a name in the input field below:
Suggestions:
First name:
Esempio spiegato
Nell'esempio sopra, quando un utente digita un carattere nel campo di input, showHint()
viene eseguita una funzione chiamata.
La funzione viene attivata onkeyup
dall'evento.
Ecco il codice:
Esempio
<p>Start typing a name in the input field below:</p>
<p>Suggestions: <span id="txtHint"></span></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
document.getElementById("txtHint").innerHTML = this.responseText;
}
xmlhttp.open("GET", "gethint.php?q=" + str);
xmlhttp.send();
}
}
</script>
Spiegazione del codice:
Innanzitutto, controlla se il campo di input è vuoto (str.length == 0). In tal caso, cancellare il contenuto del segnaposto txtHint e uscire dalla funzione.
Tuttavia, se il campo di input non è vuoto, procedere come segue:
- Creare un oggetto XMLHttpRequest
- Creare la funzione da eseguire quando la risposta del server è pronta
- Invia la richiesta a un file PHP (gethint.php) sul server
- Si noti che il parametro q è stato aggiunto gethint.php?q="+str
- La variabile str contiene il contenuto del campo di input
Il file PHP - "gethint.php"
Il file PHP controlla un array di nomi e restituisce i nomi corrispondenti al browser:
<?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 = $name;
} else {
$hint .= ", $name";
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>