ตัวอย่างฐานข้อมูล AJAX
AJAX สามารถใช้สำหรับการสื่อสารแบบโต้ตอบกับฐานข้อมูล
ตัวอย่างฐานข้อมูล AJAX
ตัวอย่างต่อไปนี้จะแสดงให้เห็นว่าหน้าเว็บสามารถดึงข้อมูลจากฐานข้อมูลด้วย AJAX ได้อย่างไร:
ตัวอย่าง
Customer info will be listed here...
ตัวอย่างที่อธิบาย - ฟังก์ชัน showCustomer()
เมื่อผู้ใช้เลือกลูกค้าในรายการดรอปดาวน์ด้านบน ฟังก์ชันที่เรียกshowCustomer()
ใช้จะถูกดำเนินการ ฟังก์ชั่นถูกทริกเกอร์โดย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();
}
ฟังก์ชันshowCustomer()
ทำสิ่งต่อไปนี้:
- ตรวจสอบว่าลูกค้าได้รับการคัดเลือก
- สร้างวัตถุ XMLHttpRequest
- สร้างฟังก์ชันที่จะดำเนินการเมื่อการตอบสนองของเซิร์ฟเวอร์พร้อม
- ส่งคำขอไปยังไฟล์บนเซิร์ฟเวอร์
- สังเกตว่ามีการเพิ่มพารามิเตอร์ (q) ลงใน URL (พร้อมเนื้อหาของรายการแบบเลื่อนลง)
หน้าเซิร์ฟเวอร์ AJAX
หน้าบนเซิร์ฟเวอร์ที่เรียกใช้โดย JavaScript ด้านบนเป็นไฟล์ PHP ชื่อ "getcustomer.php"
ซอร์สโค้ดใน "getcustomer.php" เรียกใช้แบบสอบถามกับฐานข้อมูล และส่งคืนผลลัพธ์ในตาราง 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>";
?>