Esercitazione PHP

PHP HOME Introduzione a PHP Installazione PHP Sintassi PHP Commenti PHP Variabili PHP PHP Eco/Stampa Tipi di dati PHP Stringhe PHP Numeri PHP PHP matematica Costanti PHP Operatori PHP PHP Se...Altro...Altro Passaggio PHP Ciclo PHP Funzioni PHP Array PHP Superglobali PHP RegEx PHP

Moduli PHP

Gestione dei moduli PHP Convalida del modulo PHP Modulo PHP richiesto URL/e-mail del modulo PHP Modulo PHP completo

PHP avanzato

Data e ora PHP PHP Include Gestione dei file PHP Apri/Leggi file PHP Creazione/scrittura di file PHP Caricamento file PHP Cookie PHP Sessioni PHP Filtri PHP Filtri PHP avanzati Funzioni di callback PHP PHP JSON Eccezioni PHP

PHP OOP

PHP Che cos'è OOP Classi/Oggetti PHP Costruttore PHP PHP distruttore Modificatori di accesso PHP Ereditarietà PHP Costanti PHP Classi astratte PHP Interfacce PHP Tratti PHP Metodi statici PHP Proprietà statiche PHP Spazi dei nomi PHP Iterabili PHP

Database MySQL

Database MySQL MySQL Connect MySQL Crea DB MySQL Crea tabella Dati di inserimento MySQL MySQL Ottieni l'ultimo ID MySQL inserisce più MySQL preparato MySQL Seleziona dati MySQL dove MySQL Ordina per MySQL Elimina dati Dati di aggiornamento MySQL Dati limite MySQL

PHP XML

Parser XML PHP Analizzatore PHP SimpleXML PHP SimpleXML - Ottieni PHP XML espatriato PHP XML DOM

PHP - AJAX

Introduzione all'Ajax AJAX PHP Database AJAX XML AJAX Ricerca in tempo reale AJAX Sondaggio AJAX

Esempi PHP

Esempi PHP compilatore PHP Quiz PHP Esercizi PHP Certificato PHP

Riferimento PHP

Panoramica di PHP matrice PHP Calendario PHP Data PHP Directory PHP Errore PHP Eccezione PHP File system PHP Filtro PHP PHP FTP PHP JSON Parole chiave PHP PHP Libxml Posta PHP PHP matematica PHP Varie PHP MySQLi Rete PHP Controllo dell'output PHP RegEx PHP PHP SimpleXML Flusso PHP Stringa PHP Gestione delle variabili PHP Analizzatore XML PHP Zip PHP Fuso orario PHP

PHP - AJAX e PHP


AJAX viene utilizzato per creare applicazioni più interattive.


Esempio PHP AJAX

L'esempio seguente dimostrerà 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:


Esempio spiegato

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

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 (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>Start typing a name in the input field below:</b></p>
<form action="">
  <label for="fname">First name:</label>
  <input type="text" id="fname" name="fname" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>

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 viene aggiunto all'URL (gethint.php?q="+str)
  • E 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;
?>