AJAX Database

AJAX Database Interaction

AJAX is highly effective at querying databases and displaying results interactively.

It allows users to fetch specific database records instantly, without ever refreshing the page!


The Workflow

First, the user selects an option from a dropdown menu in the HTML.

An onchange event triggers an AJAX request, passing the selected ID to a server script.

The server script connects to a SQL database, retrieves the record, and formats it as an HTML table.


Displaying the Data

Once the server script (PHP or ASP) echoes the table back to the browser, AJAX takes over.

The onload callback function catches the HTML table string and injects it directly into the DOM!

Database Interaction Example:

function showCustomer(str) {
  if (str === "") {
    document.getElementById("txtHint").innerHTML = "";
    return;
  }
  const xhttp = new XMLHttpRequest();
  xhttp.onload = function() {
    // Instantly rendering the SQL result table!
    document.getElementById("txtHint").innerHTML = this.responseText;
  }
  xhttp.open("GET", "getcustomer.php?q=" + str);
  xhttp.send();
}

Exercise 1 of 1

?

How does AJAX interact with a secure SQL database?