-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
AJAX allows web pages to dynamically load and process data from the server without reloading. One common format for server responses is XML (eXtensible Markup Language).
Although JSON is more widely used today, understanding XML is important for working with older systems or APIs that still use it.
XML is a structured format for storing data. It uses tags to define elements and their content, similar to HTML.
Example data.xml
:
<users>
<user>
<name>Vicky</name>
<age>28</age>
<email>vicky@example.com</email>
</user>
<user>
<name>Sanjana</name>
<age>25</age>
<email>sanjana@example.com</email>
</user>
</users>
In this example:
<users>
is the parent element.
Each <user>
contains <name>
, <age>
, and <email>
tags.
To load an XML file, use the XMLHttpRequest object.
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.xml", true);
xhr.onload = function() {
if (xhr.status === 200) {
let xml = xhr.responseXML; // Parse the XML file
console.log(xml);
} else {
console.error("Error loading XML file:", xhr.status);
}
};
xhr.send();
Explanation:
xhr.responseXML
automatically parses the XML into a DOM object.
You can now access nodes using standard DOM methods like getElementsByTagName()
.
Once the XML is loaded, you can traverse and extract data.
let users = xml.getElementsByTagName("user"); // Get all <user> elements
for (let i = 0; i < users.length; i++) {
let name = users[i].getElementsByTagName("name")[0].textContent;
let age = users[i].getElementsByTagName("age")[0].textContent;
let email = users[i].getElementsByTagName("email")[0].textContent;
console.log(`Name: ${name}, Age: ${age}, Email: ${email}`);
}
Explanation:
getElementsByTagName("user")
returns a NodeList of all <user>
elements.
[0]
selects the first child of the node.
textContent
extracts the text inside the tag.
You can dynamically insert XML data into the HTML using JavaScript.
<div id="output"></div>
<button id="loadBtn">Load Users</button>
<script>
document.getElementById("loadBtn").addEventListener("click", function() {
let xhr = new XMLHttpRequest();
xhr.open("GET", "data.xml", true);
xhr.onload = function() {
if (xhr.status === 200) {
let xml = xhr.responseXML;
let users = xml.getElementsByTagName("user");
let html = "";
for (let i = 0; i < users.length; i++) {
let name = users[i].getElementsByTagName("name")[0].textContent;
let age = users[i].getElementsByTagName("age")[0].textContent;
let email = users[i].getElementsByTagName("email")[0].textContent;
html += `<p>Name: ${name}, Age: ${age}, Email: ${email}</p>`;
}
document.getElementById("output").innerHTML = html;
} else {
document.getElementById("output").textContent = "Failed to load XML";
}
};
xhr.send();
});
</script>
Explanation:
Each <user>
is looped over to extract details.
The information is displayed in the <div>
dynamically without page reload.
XML files can be nested with multiple levels of tags. You can use getElementsByTagName()
repeatedly to reach nested elements.
Example:
<company>
<department>
<name>IT</name>
<employee>
<name>Vicky</name>
<role>Developer</role>
</employee>
<employee>
<name>Sanjana</name>
<role>Designer</role>
</employee>
</department>
</company>
JavaScript:
let departments = xml.getElementsByTagName("department");
for (let i = 0; i < departments.length; i++) {
let deptName = departments[i].getElementsByTagName("name")[0].textContent;
let employees = departments[i].getElementsByTagName("employee");
for (let j = 0; j < employees.length; j++) {
let empName = employees[j].getElementsByTagName("name")[0].textContent;
let role = employees[j].getElementsByTagName("role")[0].textContent;
console.log(`${deptName} - ${empName} (${role})`);
}
}
Always check the status
property to handle errors:
xhr.onload = function() {
if (xhr.status === 200) {
console.log("XML Loaded Successfully");
} else if (xhr.status === 404) {
console.error("XML file not found");
} else {
console.error("Server error:", xhr.status);
}
};
This ensures your app doesn’t break if the file is missing or the server fails.
You can also use XML responses to populate form elements dynamically.
Example: populating a <select>
with user names from XML:
let select = document.getElementById("userSelect");
let users = xml.getElementsByTagName("user");
for (let i = 0; i < users.length; i++) {
let name = users[i].getElementsByTagName("name")[0].textContent;
let option = document.createElement("option");
option.value = name;
option.textContent = name;
select.appendChild(option);
}
This makes web pages more interactive and data-driven.
AJAX with XML files allows you to:
Load structured XML data without reloading the page.
Access nested tags using getElementsByTagName()
.
Display data dynamically on the page.
Handle errors using HTTP status codes.
Integrate XML responses into forms and other UI elements.
While JSON is more common today, working with XML is still useful for legacy systems or APIs that rely on XML. Mastering XML responses gives you the foundation to handle any type of AJAX data.
Write an AJAX request to fetch data.xml
and display all <user>
names in a <div>
when a button is clicked.
Fetch data.xml
and display each user’s name, age, and email dynamically in separate <p>
elements.
Write code to loop through nested XML tags, such as <department>
and <employee>
, and log employee names with their department.
Create an AJAX request that checks for errors (404 or 500) while fetching data.xml
and displays an alert if the file is missing.
Use responseXML
to fetch XML data and populate a <select>
dropdown with user names.
Fetch an XML file and display only the users whose age is greater than 25 in a list.
Create a button that loads an XML file and appends each user’s information to an existing <div>
without replacing previous content.
Write a function that fetches XML data and converts it into JSON format using JavaScript.
Use AJAX to fetch an XML file and filter users by a specific tag value, then display the filtered results dynamically.
Write code to fetch an XML file and log both the tag names and their text content for all child elements of <user>
.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts