AJAX dapat digunakan untuk komunikasi interaktif dengan database.
Contoh berikut akan menunjukkan bagaimana halaman web dapat mengambil informasi dari database dengan AJAX:
<!DOCTYPE html> <html> <style> table,th,td { border : 1px solid black; border-collapse: collapse; } th,td { padding: 5px; } </style> <body> <h1>The XMLHttpRequest Object</h1> <form action-xhr="#"> <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) { var xhttp; if (str == "") { document.getElementById("txtHint").innerHTML = ""; return; } xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("txtHint").innerHTML = this.responseText; } }; xhttp.open("GET", "getcustomer.asp?q="+str, true); xhttp.send(); } </script> </body> </html>
Penjelasan Contoh – Fungsi showCustomer ()
Saat pengguna memilih pelanggan dalam daftar tarik-turun di atas, fungsi yang disebut “showCustomer ()” dijalankan. Fungsi ini dipicu oleh peristiwa “onchange”:
showCustomer
function showCustomer(str) { var xhttp; if (str == "") { document.getElementById("txtHint").innerHTML = ""; return; } xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("txtHint").innerHTML = this.responseText; } }; xhttp.open("GET", "getcustomer.php?q="+str, true); xhttp.send(); }
Fungsi showCustomer () melakukan hal berikut:
Halaman di server yang disebut dengan JavaScript di atas adalah file PHP yang disebut “getcustomer.php”.
Kode sumber di “getcustomer.php” menjalankan kueri terhadap database, dan mengembalikan hasilnya dalam tabel 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>"; ?>