XML, AJAX, and PHP together with a simple example:
Suppose we have an XML file named data.xml
on the server that contains information about books:
Example
<?xml version="1.0" encoding="UTF-8"?> <books> <book> <title>The Great Gatsby</title> <author>F. Scott Fitzgerald</author> <year>1925</year> </book> <book> <title>The Catcher in the Rye</title> <author>J.D. Salinger</author> <year>1951</year> </book> </books>
We want to use AJAX to fetch this XML data from a PHP script and display it on a web page.
fetchData.php
):Example
script.js
):Example
document.getElementById('fetchButton').addEventListener('click', fetchData); function fetchData() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var xmlDoc = this.responseXML; displayData(xmlDoc); } }; xhttp.open('GET', 'fetchData.php', true); xhttp.send(); } function displayData(xmlDoc) { var outputDiv = document.getElementById('output'); outputDiv.innerHTML = ''; var books = xmlDoc.getElementsByTagName('book'); for (var i = 0; i < books.length; i++) { var title = books[i].getElementsByTagName('title')[0].textContent; var author = books[i].getElementsByTagName('author')[0].textContent; var year = books[i].getElementsByTagName('year')[0].textContent; var bookInfo = 'Title: ' + title + ''; bookInfo += 'Author: ' + author + ''; bookInfo += 'Year: ' + year + ''; bookInfo += ''; outputDiv.innerHTML += bookInfo; } }
index.html
):Example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AJAX Example</title> <script src="script.js" defer></script> </head> <body> <h2>Fetch Data Using AJAX and PHP</h2> <button id="fetchButton">Fetch Data</button> <div id="output"></div> </body> </html>
fetchData()
function is called.fetchData()
, an AJAX request is made to the fetchData.php
PHP script.data.xml
file and returns it as XML data.displayData()
function is called to parse the XML response and extract book information.displayData()
function then updates the content of the <div id="output">
element with the fetched data, displaying book titles, authors, and years.This example demonstrates how to use XML, AJAX, and PHP together to fetch XML data from a server and display it dynamically on a web page