AJAX XML
Learn how to load XML data with AJAX from a PHP script and render it on a page without a full reload. Step-by-step example with XMLHttpRequest and DOM parsing.
This chapter shows how to load XML data from a PHP script using AJAX and render it on a page without a full reload. You'll build a small PHP endpoint that outputs XML, fetch it in the browser with XMLHttpRequest, parse the response with the DOM, and inject the result into the page.
If you are new to the broader topic, start with the AJAX introduction and AJAX with PHP chapters first.
What is AJAX?
AJAX (Asynchronous JavaScript and XML) is a technique that lets the browser exchange data with the server in the background and update only part of a page, instead of reloading the whole document. The browser makes an HTTP request from JavaScript, receives a response, and uses it to change the DOM. This reduces perceived latency and server load.
What is XML?
XML (Extensible Markup Language) is a text format for storing and transporting structured data using nested tags. It is human-readable and self-describing, which makes it a convenient transport format between a PHP server and the browser. When a server sends XML with a Content-Type: text/xml header, the browser parses it automatically and exposes it as a DOM tree through the responseXML property of the request.
Why use PHP, AJAX, and XML together?
In this pattern PHP queries a data source (a database or file) and emits an XML document, the browser requests that document with AJAX, and JavaScript turns the XML nodes into HTML. The result is a page that updates a region of content on demand. While XML works, most modern apps now send JSON instead because JavaScript can parse it natively — see the note in the conclusion.
How to use PHP, AJAX, and XML together
To use PHP, AJAX, and XML together, you will need to follow these steps:
- Create a PHP script that retrieves data from a database or file.
- Use AJAX to call the PHP script and retrieve the data.
- Parse the XML response in JavaScript, convert it to HTML elements, and display it on the web page.
Step 1: Create a PHP Script
The first step is to create a PHP script that retrieves data from a database or file. This script will be responsible for retrieving the data that will be displayed on the web page.
Here is an example of a PHP script that retrieves data from a database:
Example of a PHP script that retrieves data from a database
<?php
// Connect to database
$con = mysqli_connect("localhost","username","password","database");
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
// Retrieve data from database
// Note: Ensure the database contains a table named 'table' with columns: title, description, price
// Note: In production, use prepared statements to prevent SQL injection
$result = mysqli_query($con,"SELECT * FROM table");
// Set content type to XML
header('Content-Type: text/xml');
echo '<?xml version="1.0"?>';
echo '<items>';
// Loop through the results and add them to XML
while($row = mysqli_fetch_array($result)) {
echo '<item>';
echo '<title>' . htmlspecialchars($row['title']) . '</title>';
echo '<description>' . htmlspecialchars($row['description']) . '</description>';
echo '<price>' . htmlspecialchars($row['price']) . '</price>';
echo '</item>';
}
echo '</items>';
?>Note: In production, replace hardcoded credentials with environment variables and add error handling for database connections.
Step 2: Use AJAX to Call the PHP Script
The next step is to use AJAX to call the PHP script and retrieve the data. First, ensure your HTML page contains a container element where the fetched data will be injected:
<div id="data-container"></div>Here is an example of an AJAX script that calls the PHP script created in step 1:
Example of using AJAX to call a PHP script and retrieve the data
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
var xmlDoc = this.responseXML;
var items = xmlDoc.getElementsByTagName("item");
var container = document.getElementById("data-container");
container.innerHTML = ""; // Clear previous data
for (var i = 0; i < items.length; i++) {
var title = items[i].getElementsByTagName("title")[0].textContent;
var desc = items[i].getElementsByTagName("description")[0].textContent;
var price = items[i].getElementsByTagName("price")[0].textContent;
var div = document.createElement("div");
div.className = "item";
div.innerHTML = "<h3>" + title + "</h3><p>" + desc + "</p><span>" + price + "</span>";
container.appendChild(div);
}
} else {
console.error("Request failed with status: " + this.status);
var container = document.getElementById("data-container");
container.innerHTML = "<p>Error loading data.</p>";
}
}
};
xmlhttp.open("GET", "getdata.php", true);
xmlhttp.send();Note: Ensure the PHP script outputs no whitespace or BOM before the XML declaration, as this will cause this.responseXML to return null. If needed, add ob_clean(); at the start of the PHP file. If your PHP script is hosted on a different domain, ensure the server sends appropriate CORS headers (e.g., Access-Control-Allow-Origin: *).
Step 3: Format the Data and Display it on the Web Page
The browser exposes the XML response as a DOM tree via this.responseXML, so the JavaScript in Step 2 already does the parsing: getElementsByTagName("item") returns the <item> nodes, and textContent reads each child value. For a typical server response, the XML produced by the PHP script in Step 1 looks like this:
Example of formatting and displaying XML data
<items>
<item>
<title>Item 1</title>
<description>This is the description of item 1.</description>
<price>$10.00</price>
</item>
<item>
<title>Item 2</title>
<description>This is the description of item 2.</description>
<price>$20.00</price>
</item>
<item>
<title>Item 3</title>
<description>This is the description of item 3.</description>
<price>$30.00</price>
</item>
</items>After parsing, the JavaScript creates standard HTML elements (like <div>, <h3>, and <span>) which can then be styled with CSS. Here is an example of CSS that matches the generated HTML structure:
Example CSS for styling the rendered data
.item {
border: 1px solid #ccc;
padding: 10px;
margin: 10px 0;
border-radius: 4px;
}
.item h3 { margin: 0 0 5px; }
.item span { color: #2a9d8f; font-weight: bold; }Conclusion
Using PHP, AJAX, and XML together enables developers to build dynamic web pages that update specific content without full reloads. By following the steps above, you can implement this pattern to improve user experience and reduce server load.
Note: While this tutorial uses XML and XMLHttpRequest for educational purposes, modern web applications typically prefer JSON and the fetch API for AJAX data exchange due to native JavaScript support and simpler syntax. See json_encode() to produce JSON from PHP instead.
Related chapters
- AJAX Introduction — the basics of
XMLHttpRequestand the request lifecycle. - AJAX and PHP — calling PHP scripts from the browser.
- AJAX Database — fetching database rows over AJAX.
- PHP SimpleXML — parsing XML on the server side with PHP.