Make web apps dynamic - Use Ajax with PHP to fetch and send data without page reloads!
Ajax (Asynchronous JavaScript and XML) lets you communicate with a server asynchronously, updating parts of a web page without refreshing. Paired with PHP, it’s perfect for real-time features.
Ajax requires JavaScript, an XMLHttpRequest object, and a server-side script (PHP).
Basic structure: create, open, send, and handle.
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Ajax Example</title>
</head>
<body>
<button onclick="loadData()">Load Data</button>
<div id="result"></div>
<script src="script.js"></script>
</body>
</html>Instantiate XMLHttpRequest.
script.js:
function loadData() {
let xhr = new XMLHttpRequest();
// Further setup...
}Set the request method and URL.
function loadData() {
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.php", true); // true = asynchronous
// Send and handle...
}Process the server response.
function loadData() {
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.php", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("result").innerHTML = xhr.responseText;
}
};
// Start download...
}Send the request.
function loadData() {
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.php", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("result").innerHTML = xhr.responseText;
}
};
xhr.send();
}data.php:
<?php
echo "Hello from PHP!";
?>Handle older browsers (rarely needed today).
function createXHR() {
try {
return new XMLHttpRequest();
} catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP"); // IE6
} catch (e) {
return null;
}
}
}
let xhr = createXHR();Combine client and server.
data.php:
<?php
$name = "User";
echo "Welcome, $name!";
?>script.js:
function loadData() {
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.php", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("result").innerHTML = xhr.responseText;
}
};
xhr.send();
}Send parameters in the URL.
function sendData() {
let xhr = new XMLHttpRequest();
let value = "test";
xhr.open("GET", "process.php?data=" + encodeURIComponent(value), true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("result").innerHTML = xhr.responseText;
}
};
xhr.send();
}process.php:
<?php
$data = $_GET["data"] ?? "No data";
echo "Received: $data";
?>Send data in the request body.
function sendPost() {
let xhr = new XMLHttpRequest();
xhr.open("POST", "process.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("result").innerHTML = xhr.responseText;
}
};
let data = "name=Alex";
xhr.send(data);
}process.php:
<?php
$name = $_POST["name"] ?? "Guest";
echo "Hello, $name!";
?>Return and parse XML data.
xml.php:
<?php
header("Content-Type: text/xml");
echo '<?xml version="1.0" encoding="UTF-8"?>
<user>
<name>Alex</name>
<age>25</age>
</user>';
?>function loadXML() {
let xhr = new XMLHttpRequest();
xhr.open("GET", "xml.php", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
let xml = xhr.responseXML;
let name = xml.getElementsByTagName("name")[0].textContent;
document.getElementById("result").innerHTML = "Name: " . name;
}
};
xhr.send();
}Generate and process XML.
xml-process.php:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$xml = simplexml_load_string(file_get_contents("php://input"));
$name = (string)$xml->name;
echo "Processed: $name";
}
?>function sendXML() {
let xhr = new XMLHttpRequest();
xhr.open("POST", "xml-process.php", true);
xhr.setRequestHeader("Content-Type", "text/xml");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("result").innerHTML = xhr.responseText;
}
};
let xml = '<?xml version="1.0"?><user><name>Bella</name></user>';
xhr.send(xml);
}| Task | Tool | Example Use Case |
|---|---|---|
| Create XHR | new XMLHttpRequest() |
Start Ajax |
| GET Data | xhr.open("GET") |
Fetch simple data |
| POST Data | xhr.open("POST") |
Send form data |
| Handle XML | responseXML |
Structured responses |
- Async: Use
truefor non-blocking requests. - Security: Validate and sanitize server-side data.
- Error Handling: Check
xhr.status(e.g., 404, 500). - Modernity: Consider
fetch()API for newer projects.
Error Handling Example:
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
document.getElementById("result").innerHTML = xhr.responseText;
} else {
document.getElementById("result").innerHTML = "Error: " + xhr.status;
}
}
};