Ajax Php in XML
? AJAX with PHP and XML – Complete Guide
This example demonstrates how to use AJAX to fetch data from a PHP script, which returns the data in XML format, and how to display that XML dynamically using JavaScript — without reloading the page.
? Workflow Overview
User triggers an AJAX request (e.g., page load or button click).
JavaScript sends a request to a PHP script.
The PHP script fetches or generates data and returns it as XML.
JavaScript receives the XML response and updates the HTML.
? Step-by-Step Example
? data.php — PHP Script Returning XML
<?phpheader("Content-Type: text/xml");echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";?><students> <student> <name>Vikash Gupta</name> <grade>A</grade> </student> <student> <name>Ravi Kumar</name> <grade>B+</grade> </student></students>? index.html — HTML + AJAX to Load XML from PHP
<!DOCTYPE html><html><head> <title>AJAX + PHP + XML Example</title></head><body><h2>Student Grades (via AJAX + PHP + XML)</h2><button onclick="loadStudents()">Load Students</button><div id="result"></div><script>function loadStudents() { const xhttp = new XMLHttpRequest(); xhttp.onload = function () { const xml = this.responseXML; const students = xml.getElementsByTagName("student"); let output = "<ul>"; for (let i = 0; i < students.length; i++) { const name = students[i].getElementsByTagName("name")[0].textContent; const grade = students[i].getElementsByTagName("grade")[0].textContent; output += `<li>${name} - Grade: ${grade}</li>`; } output += "</ul>"; document.getElementById("result").innerHTML = output; }; xhttp.open("GET", "data.php", true); xhttp.send();}</script></body></html>? Output
When the button is clicked:
AJAX sends a request to
data.phpPHP sends back XML containing student info
JavaScript parses and displays the data in a list
? Tips
Always set the
Content-Type: text/xmlin the PHP header.Use
responseXMLto automatically parse XML.Ensure XML is well-formed — even one extra space outside tags can break it.
? Optional Extensions
Would you like examples of:
AJAX + PHP + MySQL (with dynamic XML)?
Sending form data to PHP and returning XML?
Comparing this with AJAX + JSON?
Let me know how you'd like to build on this!