Load Dynamic Data with AJAX, Fetch API, and PHP 🚀
If you’re developing a website with HTML, JavaScript, and PHP, you might need to load data dynamically without refreshing the page.
One of the most modern and efficient ways to achieve this is by using the Fetch API instead of the old XMLHttpRequest.
Why Use the Fetch API?
✅ Faster and simpler than XMLHttpRequest
✅ Supported by all modern browsers
✅ Cleaner and more readable code
In this guide, I’ll show you how to retrieve data from a MySQL database using PHP and AJAX with Fetch API.
1️⃣ Creating the PHP API
First, create a PHP file (data.php) that fetches data from a MySQL database and returns it as JSON.
<?php
header('Content-Type: application/json'); // Set response type to JSON
$conn = new mysqli("localhost", "username", "password", "database");
if ($conn->connect_error) {
die(json_encode(["error" => "Connection failed"]));
}
$sql = "SELECT id, name FROM users";
$result = $conn->query($sql);
$data = [];
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
echo json_encode($data);
$conn->close();
?>
🔹 This PHP script connects to the database and returns the data in JSON format.
2️⃣ Creating the Frontend with AJAX (Fetch API)
Now, let’s create an HTML page with a button to fetch data using Fetch API.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX with Fetch and PHP</title>
</head>
<body>
<h2>User List</h2>
<button onclick="loadData()">Load Users</button>
<ul id="user-list"></ul>
<script>
function loadData() {
fetch('data.php')
.then(response => response.json()) // Convert response to JSON
.then(data => {
let list = document.getElementById('user-list');
list.innerHTML = ''; // Clear the list
data.forEach(user => {
let li = document.createElement('li');
li.textContent = user.name;
list.appendChild(li);
});
})
.catch(error => console.error("Error:", error));
}
</script>
</body>
</html>
🔹 Clicking the button calls the loadData() function, which uses fetch() to get the data from our PHP API.
🔹 The data is displayed dynamically in a list without refreshing the page.
3️⃣ Why This Method is Useful
💡 Better performance compared to XMLHttpRequest
💡 Cleaner and more readable code
💡 Compatible with all modern browsers
Conclusion
By leveraging the Fetch API and PHP, you can load data in real time without refreshing the page, making your website more fluid and faster. 🚀
