Welcome to our comprehensive PHP AJAX Database tutorial! In this lesson, we'll dive deep into using AJAX with PHP to interact with databases, creating a dynamic and responsive web application. Let's get started! π
AJAX, Asynchronous JavaScript and XML, is a technique used to update parts of a web page without reloading the entire page. This makes the web application more responsive and smoother for the user.
PHP is a server-side scripting language used to create dynamic web pages. AJAX allows PHP to communicate with the client-side JavaScript, updating parts of the web page without reloading the entire page.
index.html and ajax.php.index.html file and let's create the HTML structure for our web page.<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP AJAX Database Example</title>
</head>
<body>
<!-- Our HTML structure will be here -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="ajax.js"></script>
</body>
</html>ajax.php file, let's write the PHP code to connect to the database and fetch data.<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to select data from the table
$sql = "SELECT id, name FROM users";
$result = $conn->query($sql);
// Fetch data as an associative array
$users = [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$users[] = $row;
}
}
// Close the connection
$conn->close();
?>ajax.js file, let's write the JavaScript code to use AJAX to fetch data from the PHP script.$(document).ready(function(){
// Function to fetch data from PHP script using AJAX
function fetchData() {
$.ajax({
url: 'ajax.php',
method: 'GET',
success: function(data) {
// Parse JSON data and append HTML to the container
const users = JSON.parse(data);
let html = '<ul id="user-list">';
users.forEach(user => {
html += `<li id="user-${user.id}">${user.name}</li>`;
});
html += '</ul>';
$('#user-container').html(html);
}
});
}
// Call the function to fetch data when the page loads
fetchData();
});index.html file, let's create a container for our dynamic user list.<div id="user-container"></div>What is AJAX?
In this tutorial, we learned how to use AJAX with PHP to interact with databases, creating a dynamic and responsive web application. We connected to a MySQL database, fetched data, and used AJAX to update parts of the web page without reloading the entire page. Now, you're ready to take this knowledge and create your own dynamic web applications! π