Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

AJAX Database

AJAX can be used for dynamic communication with a database.

AJAX Database Example

The following example demonstrates how a web page can retrieve information from a database using AJAX.

Example

Customer information will be displayed here…

Example Explained – The showCustomer() Function

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

showCustomer

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();
}

The showCustomer() function performs the following steps:

 

  • Checks if a customer is selected.
  • Creates an XMLHttpRequest object.
  • Defines the function to be executed when the server response is ready.
  • Sends the request to a file on the server.
  • Adds a parameter (q) to the URL, containing the selected value from the dropdown list.

The AJAX Server Page

The server-side page called by the JavaScript above is a PHP file named “getcustomer.php”.

The code in “getcustomer.php” executes a query on the database and returns the result in an HTML table.

<?php
$mysqli = new mysqli(servernameusernamepassworddbname);
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>”;
?>