AJAX kan användas för interaktiv kommunikation med en databas.
Följande exempel visar hur en webbsida kan hämtas information från en databas med AJAX:
Prova själv →
<!DOCTYPE html>
<html>
<style>
th,td {
padding: 5px;
}
</style>
<body>
<h2>The XMLHttpRequest Object</h2>
<form action="">
<select name="customers" onchange="showCustomer(this.value)">
<option value="">Select a customer:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
</form>
<br>
<div id="txtHint">Customer info will be listed here...</div>
<script>
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();
}
</script>
</body>
</html>
När en användare väljer en kund i rullgardinsmenyn ovan, exekveras en funktion som heter showCustomer()
. De funktionen utlöses av händelsen onchange
:
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();
}
Funktionen showCustomer()
gör följande:
Kontrollera om en kund är vald
Skapa ett XMLHttpRequest-objekt
Skapa funktionen som ska köras när serversvaret är klart
Skicka förfrågan till en fil på servern
Observera att en parameter (q) läggs till i URL:en (med innehållet i rullgardinsmenyn)
Sidan på servern som anropas av JavaScript ovan är en PHP-fil som heter "getcustomer.php".
Källkoden i "getcustomer.php" kör en fråga mot en databas och returnerar resultatet i en HTML tabell:
<?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>";
?>