Esempio di database AJAX
AJAX può essere utilizzato per la comunicazione interattiva con un database.
Esempio di database AJAX
L'esempio seguente dimostrerà come una pagina Web può recuperare informazioni da un database con AJAX:
Esempio
Customer info will be listed here...
Esempio spiegato - La funzione showCustomer()
Quando un utente seleziona un cliente nell'elenco a discesa sopra, showCustomer()
viene eseguita una funzione chiamata. La funzione è attivata onchange
dall'evento:
mostraCliente
function showCustomer(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("txtHint").innerHTML = this.responseText;
}
xhttp.open("GET", "getcustomer.php?q="+str);
xhttp.send();
}
La showCustomer()
funzione esegue le seguenti operazioni:
- Verifica se un cliente è selezionato
- Creare un oggetto XMLHttpRequest
- Creare la funzione da eseguire quando la risposta del server è pronta
- Invia la richiesta a un file sul server
- Si noti che un parametro (q) viene aggiunto all'URL (con il contenuto dell'elenco a discesa)
La pagina del server AJAX
La pagina sul server chiamata dal JavaScript sopra è un file PHP chiamato "getcustomer.php".
Il codice sorgente in "getcustomer.php" esegue una query su un database e restituisce il risultato in una tabella HTML:
<?php
$mysqli = new mysqli("servername", "username",
"password", "dbname");
if($mysqli->connect_error) {
exit('Could not connect');
}
$sql = "SELECT customerid, companyname,
contactname, address, city, postalcode, country
FROM customers WHERE
customerid = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $_GET['q']);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($cid,
$cname, $name, $adr, $city, $pcode, $country);
$stmt->fetch();
$stmt->close();
echo "<table>";
echo "<tr>";
echo "<th>CustomerID</th>";
echo
"<td>" . $cid . "</td>";
echo "<th>CompanyName</th>";
echo "<td>" . $cname
. "</td>";
echo "<th>ContactName</th>";
echo "<td>" . $name . "</td>";
echo "<th>Address</th>";
echo "<td>" .
$adr . "</td>";
echo "<th>City</th>";
echo "<td>" . $city . "</td>";
echo "<th>PostalCode</th>";
echo "<td>" .
$pcode . "</td>";
echo "<th>Country</th>";
echo "<td>" . $country .
"</td>";
echo "</tr>";
echo "</table>";
?>