JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Ajax Database


AJAX allows web pages to send and receive data from the server without reloading, and combining it with a database lets web applications fetch or store data dynamically. This makes websites interactive and user-friendly.

For example, Vicky can build a user management system where Sanjana enters her details, and they are saved to the database and displayed instantly.

What Is AJAX Database Interaction?

AJAX database interaction refers to using AJAX requests in JavaScript to communicate with server-side scripts (PHP, ASP, etc.) that perform database operations. Common tasks include:

  • Retrieving data from a database.

  • Inserting new records.

  • Updating existing records.

  • Deleting records dynamically.

The server-side script executes the database queries and returns the results, often in JSON or plain text format. The browser then processes the response without page reload.

Setting Up the Database

Let’s assume we have a MySQL database named testdb with a table called users:

CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(50),
  email VARCHAR(50)
);

We want to add new users and display existing users dynamically using AJAX.

Fetching Data from the Database

PHP File (fetch_users.php)

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Fetch users
$sql = "SELECT name, email FROM users";
$result = $conn->query($sql);

$users = array();

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $users[] = $row;
    }
}

// Return JSON
header('Content-Type: application/json');
echo json_encode($users);

$conn->close();
?>

JavaScript

function loadUsers() {
  let xhr = new XMLHttpRequest();
  xhr.open("GET", "fetch_users.php", true);

  xhr.onload = function() {
    if (xhr.status === 200) {
      let users = JSON.parse(xhr.responseText);
      let html = "";
      users.forEach(user => {
        html += `<p>Name: ${user.name}, Email: ${user.email}</p>`;
      });
      document.getElementById("userList").innerHTML = html;
    } else {
      document.getElementById("userList").textContent = "Failed to load users";
    }
  };

  xhr.send();
}

document.addEventListener("DOMContentLoaded", loadUsers); // Load users on page load

Explanation:

  • PHP connects to the database, fetches data, and returns it as JSON.

  • JavaScript parses the JSON and dynamically displays user data.

Inserting Data into the Database

HTML Form

<input type="text" id="name" placeholder="Enter name">
<input type="email" id="email" placeholder="Enter email">
<button id="addUser">Add User</button>
<div id="message"></div>

JavaScript

document.getElementById("addUser").addEventListener("click", function() {
  let name = document.getElementById("name").value;
  let email = document.getElementById("email").value;

  let xhr = new XMLHttpRequest();
  xhr.open("POST", "add_user.php", true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

  xhr.onload = function() {
    if (xhr.status === 200) {
      document.getElementById("message").textContent = xhr.responseText;
      loadUsers(); // Refresh user list
    } else {
      document.getElementById("message").textContent = "Error adding user";
    }
  };

  xhr.send(`name=${encodeURIComponent(name)}&email=${encodeURIComponent(email)}`);
});

PHP File (add_user.php)

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testdb";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

if(isset($_POST['name']) && isset($_POST['email'])){
    $name = $conn->real_escape_string($_POST['name']);
    $email = $conn->real_escape_string($_POST['email']);

    $sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
    if ($conn->query($sql) === TRUE) {
        echo "User added successfully!";
    } else {
        echo "Error: " . $conn->error;
    }
} else {
    echo "Please provide name and email.";
}

$conn->close();
?>

Explanation:

  • The form sends data via AJAX POST.

  • PHP inserts the new user into the database.

  • JavaScript refreshes the displayed user list without reloading the page.

Updating and Deleting Records

Similarly, AJAX can be used to update or delete database records dynamically. For example:

  • update_user.php – Receives user ID and new data, updates the database, and returns a success message.

  • delete_user.php – Receives user ID, deletes the record, and returns confirmation.

All updates are handled asynchronously, keeping the user interface smooth.

Benefits of AJAX Database

  • No page reload is required when fetching or submitting data.

  • Real-time updates make web applications more interactive.

  • Users like Sanjana can see changes immediately after Vicky adds new records.

  • Works with plain text, JSON, or HTML responses from the server.

Summary of the Tutorial

Using AJAX with databases, developers can:

  • Retrieve and display data dynamically.

  • Insert, update, and delete records without page refresh.

  • Handle JSON or plain text responses for smooth interactions.

  • Build interactive applications like user management systems, live search, and dashboards.

This approach allows Vicky to create a responsive interface where Sanjana can interact with the database instantly, enhancing the user experience.


Practice Questions

  1. Write an AJAX GET request to fetch all users from fetch_users.php and display them in a <div> on page load.

  2. Create a form to add a new user (name and email) and send the data via AJAX POST to add_user.php, then update the user list dynamically.

  3. Write an AJAX request to fetch users in JSON format and display only those whose name is “Sanjana”.

  4. Create a button that deletes a specific user by sending their ID via AJAX POST to delete_user.php and refreshes the list.

  5. Write an AJAX request to update a user’s email using update_user.php and display a success message.

  6. Fetch the user list and display it in a table with columns for name and email using AJAX.

  7. Write code to handle errors if fetch_users.php is missing or the database connection fails, and display an error message in a <div>.

  8. Create a search input that fetches matching users from the database via AJAX as the user types.

  9. Write an AJAX POST request to insert multiple users at once using a form and display a confirmation message.

  10. Create a function that refreshes the user list every 10 seconds using AJAX to show newly added records without page reload.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top