AJAX (Asynchronous JavaScript and XML) is a powerful technique for creating dynamic web applications that update content without requiring a full page reload. When combined with PHP, a versatile server-side scripting language, AJAX enables seamless communication between the client and server. This tutorial provides a minimal PHP AJAX example to demonstrate how to fetch data dynamically.
Why Use AJAX with PHP?
AJAX allows web pages to send and receive data in the background, improving user experience by making interactions faster and more fluid. PHP, as a server-side language, processes requests and delivers dynamic content, making it an ideal partner for AJAX-driven applications.
Here’s a minimal PHP with AJAX example:
Save below file as index.php or index.html
<!DOCTYPE html>
<html>
<head>
<title>Simple AJAX Example</title>
</head>
<body>
<button onclick="loadData()">Load Data</button>
<div id="result"></div>
<script>
function loadData() {
// Create XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Configure the request
xhr.open('GET', 'get_data.php', true);
// Set up callback for when request completes
xhr.onload = function() {
if (xhr.status === 200) {
document.getElementById('result').innerHTML = xhr.responseText;
}
};
// Send the request
xhr.send();
}
</script>
</body>
</html>
PHP File (get_data.php)
<?php
// Set content type header
header('Content-Type: text/plain');
// Simulate some data processing
$current_time = date('H:i:s');
$random_number = rand(1, 100);
// Return the data
echo "Server time: $current_time\nRandom number: $random_number";
?>
How it works:
- User clicks the button → triggers
loadData()
function - AJAX request is sent to
get_data.php
- PHP script processes the request and returns data
- Response is displayed in the
#result
div
Key points:
- The page doesn’t refresh
- Data is fetched asynchronously
- PHP handles the server-side processing
- JavaScript handles the client-side interaction
This is a basic example using vanilla JavaScript. In real applications, you might want to use libraries like jQuery or modern fetch()
API for more robust AJAX handling.