πŸ“‚ AJAX Application Development
Estimated reading: 5 minutes 119 views

πŸ—ƒοΈ AJAX – Database Operations Using PHP with MySQL and AJAX


🧲 Introduction – Why Use AJAX with PHP and MySQL?

Using AJAX with PHP and MySQL allows developers to perform database operations asynchronouslyβ€”without refreshing the entire page. This is incredibly useful in modern web apps where user interaction needs to be smooth, responsive, and dynamic.

Whether you’re building a CRUD app, live search, or a dynamic dashboard, this combination allows seamless backend communication and database manipulation via background requests.

🎯 In this guide, you’ll learn:

  • How to fetch, insert, update, and delete data with AJAX + PHP + MySQL
  • Complete examples using fetch() and XMLHttpRequest
  • How to structure front-end JavaScript and backend PHP logic
  • Tips for securing and validating input

🧱 Project Overview

/ajax-db-app
β”‚
β”œβ”€β”€ index.html          ← User interface
β”œβ”€β”€ script.js           ← AJAX code
β”œβ”€β”€ db.php              ← DB connection file
β”œβ”€β”€ insert.php          ← Handles data insertion
β”œβ”€β”€ fetch.php           ← Fetches data from DB
β”œβ”€β”€ delete.php          ← Deletes records
└── update.php          ← Updates records

βœ… These files create a basic CRUD application powered by AJAX.


🧾 Step 1: Create Database and Table (MySQL)

CREATE DATABASE ajax_demo;
USE ajax_demo;

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

βœ… This will store user records we’ll manage through AJAX.


πŸ”§ Step 2: Database Connection (db.php)

<?php
$conn = new mysqli("localhost", "root", "", "ajax_demo");
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
?>

πŸ“₯ Step 3: Insert Data (insert.php)

<?php
include "db.php";

$name = $_POST['name'];
$email = $_POST['email'];

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

πŸ” Step 4: Fetch Data (fetch.php)

<?php
include "db.php";

$result = $conn->query("SELECT * FROM users");
$data = "";

while ($row = $result->fetch_assoc()) {
  $data .= "<tr>
              <td>{$row['id']}</td>
              <td>{$row['name']}</td>
              <td>{$row['email']}</td>
              <td>
                <button onclick='deleteUser({$row['id']})'>Delete</button>
              </td>
           </tr>";
}

echo $data;
?>

🧹 Step 5: Delete User (delete.php)

<?php
include "db.php";
$id = $_POST['id'];

$sql = "DELETE FROM users WHERE id = $id";
echo ($conn->query($sql)) ? "User deleted." : "Deletion failed.";
?>

🧾 Step 6: Front-End UI (index.html)

<form id="userForm">
  <input type="text" name="name" placeholder="Name" required />
  <input type="email" name="email" placeholder="Email" required />
  <button type="submit">Add User</button>
</form>

<table border="1">
  <thead>
    <tr><th>ID</th><th>Name</th><th>Email</th><th>Actions</th></tr>
  </thead>
  <tbody id="userTable"></tbody>
</table>

<script src="script.js"></script>

πŸ” Step 7: AJAX Script (script.js)

document.getElementById("userForm").addEventListener("submit", function (e) {
  e.preventDefault();
  const formData = new FormData(this);

  fetch("insert.php", {
    method: "POST",
    body: formData
  })
    .then(res => res.text())
    .then(msg => {
      alert(msg);
      this.reset();
      loadUsers();
    });
});

function loadUsers() {
  fetch("fetch.php")
    .then(res => res.text())
    .then(data => {
      document.getElementById("userTable").innerHTML = data;
    });
}

function deleteUser(id) {
  const formData = new FormData();
  formData.append("id", id);

  fetch("delete.php", {
    method: "POST",
    body: formData
  })
    .then(res => res.text())
    .then(msg => {
      alert(msg);
      loadUsers();
    });
}

loadUsers(); // Initial load

βœ… What You Can Build with This Stack

FeatureDescription
Live data tablesLoad and refresh content without reloads
Comment systemsAdd/view/delete comments dynamically
User management dashboardsPerform CRUD via background requests
Product catalog filtersDynamically filter/search without reload

πŸ” Security and Validation Tips

  • βœ… Use prepared statements to prevent SQL injection
  • βœ… Validate input on both client-side and server-side
  • βœ… Sanitize all POST/GET values
  • βœ… Use CSRF tokens for sensitive AJAX requests

πŸ“Œ Summary – Recap & Takeaways

AJAX combined with PHP and MySQL provides a robust and responsive way to perform database operations. This setup allows users to interact with data in real time, improving usability without overloading the server.

πŸ” Key Takeaways:

  • Use fetch() or XMLHttpRequest to submit/receive data asynchronously
  • PHP handles database queries and returns output as HTML/JSON
  • MySQL serves as a scalable backend for dynamic data storage

βš™οΈ Next Steps:

  • Add pagination and search filters using AJAX
  • Use JSON instead of HTML for better frontend control
  • Implement edit/update functionality with modal forms

❓ FAQs – AJAX and MySQL Integration with PHP


❓ Can I send JSON from JavaScript to PHP?
βœ… Yes. Use fetch() with Content-Type: application/json and decode on PHP with json_decode().


❓ Is MySQL fast enough for real-time AJAX requests?
βœ… Yes, for moderate load. Use indexes and optimized queries for scalability.


❓ Can I use PDO instead of mysqli?
βœ… Absolutely. PDO is more secure and flexible with prepared statements.


❓ How do I prevent SQL injection in AJAX apps?
βœ… Always use prepared statements (mysqli or PDO) and validate inputs.


❓ Is it better to return HTML or JSON from PHP?
βœ… JSON is recommended for cleaner separation of data and view layers.


Share Now :
Share

AJAX – Database Operations Using PHP with MySQL and AJAX

Or Copy Link

CONTENTS
Scroll to Top