Gli ultimi tutorial di sviluppo web
 

PHP - AJAX e PHP


AJAX viene utilizzato per creare applicazioni più interattive.


AJAX PHP Esempio

Il seguente esempio dimostrerà come una pagina web in grado di comunicare con un server web, mentre un tipo di utente caratteri in un campo di input:

Esempio

Start typing a name in the input field below:

First name:

Suggestions:


esempio spiegato

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

La funzione viene attivata dall'evento onKeyUp.

Ecco il codice HTML:

Esempio

<html>
<head>
<script>
function showHint(str) {
    if (str.length == 0) {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
            }
        };
        xmlhttp.open("GET", "gethint.php?q=" + str, true);
        xmlhttp.send();
    }
}
</script>
</head>
<body>

<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
Esempio Run »

Codice spiegazione:

In primo luogo, verificare se il campo di input è vuota (str.length == 0) . Se lo è, cancellare il contenuto del segnaposto txtHint e uscire dalla funzione.

Tuttavia, se il campo di ingresso non è vuoto, effettuare le seguenti operazioni:

  • Creare un oggetto XMLHttpRequest
  • Creare la funzione da eseguire quando la risposta del server è pronto
  • Inviare la richiesta via ad un file PHP (gethint.php) sul server
  • Si noti che il parametro q viene aggiunto gethint.php? Q = "+ str
  • La variabile str contiene il contenuto del campo di input

Il PHP File - "gethint.php"

Il file PHP controlla una serie di nomi, e restituisce il relativo name(s) 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;
?>