AJAX and Database

AJAX (Asynchronous JavaScript and XML) is a powerful technology that enables web pages to update content asynchronously by exchanging data with a web server behind the scenes. This means you can update parts of a web page without reloading the whole page. A common use case of AJAX is retrieving or sending data to a database without refreshing the web page.

In this tutorial, we’ll cover how AJAX interacts with a database using a simple example: a form that sends data to the server and retrieves data from a MySQL database.


How AJAX Works

Here’s a basic flow of how AJAX interacts with a database:

  1. User interacts with the web page (e.g., clicks a button or submits a form).
  2. JavaScript captures the event and sends an AJAX request to a server-side script (usually written in PHP, Python, Node.js, etc.).
  3. The server-side script queries the database (like MySQL) and returns a response.
  4. JavaScript processes the response and updates the HTML content accordingly.

Example Scenario

We will create a simple AJAX-powered form that allows users to search for user names stored in a MySQL database.

1. HTML Form

htmlCopyEdit<input type="text" id="search" placeholder="Search user...">
<div id="results"></div>

2. JavaScript + AJAX

javascriptCopyEditdocument.getElementById('search').addEventListener('keyup', function () {
    const query = this.value;

    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'search.php?q=' + query, true);
    xhr.onload = function () {
        if (xhr.status === 200) {
            document.getElementById('results').innerHTML = xhr.responseText;
        }
    };
    xhr.send();
});

This script sends the search query to search.php whenever a key is pressed in the input box. The server responds with matching results from the database.


3. Server-Side Script (PHP + MySQL)

Here’s the search.php file that interacts with the database:

phpCopyEdit<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'ajax_example';

$conn = new mysqli($host, $user, $pass, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$search = $_GET['q'];
$search = $conn->real_escape_string($search);

$sql = "SELECT name FROM users WHERE name LIKE '%$search%'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "<p>" . $row['name'] . "</p>";
    }
} else {
    echo "<p>No results found</p>";
}
$conn->close();
?>

This PHP script connects to a MySQL database and runs a search query based on user input. It returns matching names in HTML format.

Leave a Reply

Your email address will not be published. Required fields are marked *