HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
AJAX can be used for interactive communication with a database
The following example will demonstrate how a web page can fetch information from a database with AJAX:
When a user selects a customer in the dropdown list above, a function called "showCustomer()" is executed. The function is triggered by the "onchange" event:
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?q="+str, true);
xhttp.send();
}
The showCustomer() function does the following:
The page on the server called by the JavaScript above is an PHP file called "getcustomer".
The source code in "getcustomer" runs a query against a database, and returns the result in an HTML table:
<?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>";
?>