AJAX Database
Connecting to databases with AJAX
🗄️ What is AJAX Database?
AJAX Database allows web pages to communicate with server-side databases without reloading. You can fetch, insert, update, and delete data dynamically, creating interactive database-driven applications.
// Simple AJAX database request
fetch('get-users.php')
.then(response => response.json())
.then(data => console.log(data));
Key Database Operations
Read (SELECT)
Fetch data from database
fetch('api/users.php')
Create (INSERT)
Add new records to database
fetch('api/add.php', {
method: 'POST'
})
Update
Modify existing records
fetch('api/update.php', {
method: 'PUT'
})
Delete
Remove records from database
fetch('api/delete.php', {
method: 'DELETE'
})
🔹 Fetching Database Records
Use AJAX to retrieve data from a database without page reload. The server-side script queries the database and returns results in JSON format, which JavaScript can easily process and display on your webpage.
// Fetch users from database
function getUsers() {
fetch('get-users.php')
.then(response => response.json())
.then(users => {
users.forEach(user => {
console.log(user.name);
});
})
.catch(error => console.error('Error:', error));
}
Output:
John Doe
Jane Smith
Bob Johnson
🔹 Server-Side PHP Example
The server-side script connects to the database, executes queries, and returns data. This PHP example shows a basic database connection and query execution that works with the AJAX request from the client side.
<?php
// get-users.php
header('Content-Type: application/json');
$conn = new mysqli("localhost", "user", "pass", "mydb");
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
$users = array();
while($row = $result->fetch_assoc()) {
$users[] = $row;
}
echo json_encode($users);
$conn->close();
?>
🔹 Inserting Data with AJAX
Send new data to the database using POST method. The FormData object collects form inputs, and the server-side script processes the data and inserts it into the database, returning a success or error message.
// Add new user to database
function addUser(name, email) {
const formData = new FormData();
formData.append('name', name);
formData.append('email', email);
fetch('add-user.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if(data.success) {
alert('User added successfully!');
}
});
}
Output:
✓ User added successfully!
🔹 Real-Time Search Example
Create a live search feature that queries the database as users type. Each keystroke triggers an AJAX request to search the database, providing instant results without page refresh, enhancing user experience significantly.
<!-- HTML -->
<input type="text" id="search" placeholder="Search users...">
<div id="results"></div>
<script>
document.getElementById('search').addEventListener('input', function() {
const query = this.value;
fetch(`search.php?q=${query}`)
.then(response => response.json())
.then(data => {
document.getElementById('results').innerHTML =
data.map(user => `<p>${user.name}</p>`).join('');
});
});
</script>