JavaScript AJAX Database
JavaScript Basics

JavaScript AJAX Database

AJAX Database Example

AJAX can be used for interactive communication with a database.

AJAX Database Example

The following example demonstrates how a web page can fetch information from a database using AJAX:


Select a customer:

Customer info will be listed here...

Example Explained - The showCustomer() Function

When a user selects a customer from the dropdown list above, a function called showCustomer() is executed. This function is triggered by the onchange event:

JavaScript Code:

function showCustomer(str) {  if (str == "") {    document.getElementById("txtHint").innerHTML = "";    return;  }  
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {  
document.getElementById("txtHint").innerHTML = this.responseText;  }"GET", "getcustomer.php?q=" + str); 

Function Explanation:

  1. Check if a customer is selected. If not, clear the content of the txtHint placeholder and exit the function.
  2. Create an XMLHttpRequest object.
  3. Define the function to be executed when the server response is ready.
  4. Send the request to a file on the server, adding a parameter (q) to the URL with the content of the dropdown list.

The AJAX Server Page

The page on the server called by the JavaScript above is a PHP file named "getcustomer.php".

The source code in "getcustomer.php" runs a query against a database and returns the result in an HTML table:

PHP Code:

$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->bind_result($cid, $cname, $name, $adr, $city, $pcode, $country);

echo "<table>";
echo "<tr><th>CustomerID</th><td>" . $cid . "</td></tr>";
echo "<tr><th>CompanyName</th><td>" . $cname . "</td></tr>";
echo "<tr><th>ContactName</th><td>" . $name . "</td></tr>";
echo "<tr><th>Address</th><td>" . $adr . "</td></tr>";
echo "<tr><th>City</th><td>" . $city . "</td></tr>";
echo "<tr><th>PostalCode</th><td>" . $pcode . "</td></tr>";
echo "<tr><th>Country</th><td>" . $country . "</td></tr>";
echo "</table>";

This code provides a real-time way to fetch and display customer information from a database based on user input, making the application more interactive and responsive.

Take a look into your desired course