AJAX (Asynchronous JavaScript and XML) is a technique used to create dynamic, interactive web applications. It allows web pages to update specific parts without reloading the entire page. PHP commonly works with AJAX to handle server-side logic asynchronously.
AJAX works by sending HTTP requests using JavaScript. PHP receives the request, processes data, and returns a response (HTML or JSON). JavaScript then updates the page dynamically.
// HTML elements and JavaScript AJAX request
<button onclick="loadData()">Get Data</button>
<div id="response"></div>
// AJAX function using XMLHttpRequest
function loadData() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "data.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("response").innerHTML = xhr.responseText;
}
};
xhr.send();
}
// PHP script responding to AJAX request
<?php
echo "Hello, this is data returned from PHP!";
?>
When the button is clicked, JavaScript sends an asynchronous request to the PHP file. The PHP script responds with text, which is inserted into the page without refreshing.
You can replace XMLHttpRequest with the modern fetch() API to perform cleaner and promise-based AJAX requests.
// Modern fetch() implementation
function loadData() {
fetch('data.php')
.then(response => {
if (!response.ok) throw new Error('Network response was not ok');
return response.text();
})
.then(data => {
document.getElementById("response").innerHTML = data;
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
}
fetch() instead of XMLHttpRequest