Skip to content

XML HTTP Request

Web applications often need to dynamically load XML data from a server without requiring a full page refresh. This is commonly achieved using JavaScript’s networking capabilities.

Two primary mechanisms exist in modern browsers: the older XMLHttpRequest object and the newer fetch API.

fetch provides a more powerful and flexible interface for network requests, based on Promises.

Key advantages:

  • Cleaner, Promise-based syntax (easier async handling with then/catch or async/await).
  • More flexible request/response objects.
  • Considered the modern standard for making requests.

Example: Fetching and parsing XML using fetch:

Section titled “Example: Fetching and parsing XML using fetch:”
async function fetchXmlData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
// Check content type if needed (optional)
const contentType = response.headers.get('content-type');
if (!contentType || (!contentType.includes('application/xml') && !contentType.includes('text/xml'))) {
console.warn(`Expected XML, but received Content-Type: ${contentType}`);
}
const xmlText = await response.text();
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlText, "application/xml");
// Check for parsing errors
const parseError = xmlDoc.querySelector('parsererror');
if (parseError) {
console.error('Error parsing XML:', parseError);
throw new Error('Failed to parse XML');
}
console.log('Successfully fetched and parsed XML:');
// Now you can process the xmlDoc (e.g., extract data)
console.log(xmlDoc.documentElement.nodeName); // Logs the root element name
return xmlDoc;
} catch (error) {
console.error('Error fetching or parsing XML:', error);
return null; // Or handle the error appropriately
}
}
// Usage:
fetchXmlData('/api/data.xml') // Example URL
.then(doc => {
if (doc) {
// Do something with the parsed XML document
}
});

2. The XMLHttpRequest Object (Legacy/Traditional Approach)

Section titled “2. The XMLHttpRequest Object (Legacy/Traditional Approach)”

The XMLHttpRequest (XHR) object was the original way to make asynchronous requests from JavaScript. While fetch is generally preferred now, XHR is still widely supported and used in older codebases or for features not yet fully covered by fetch (like detailed progress events).

Core concept: You create an XHR object, configure it (open), set up event handlers (onload, onerror), and send the request (send).

Example: Fetching XML using XMLHttpRequest:

Section titled “Example: Fetching XML using XMLHttpRequest:”
function loadXmlWithXHR(url) {
const xhr = new XMLHttpRequest();
// Configure the request: GET method, URL, asynchronous true
xhr.open('GET', url, true);
// Set up event handler for when the request completes successfully
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
// Check if responseXML is available (browser-parsed XML)
if (xhr.responseXML) {
console.log('Successfully received parsed XML (responseXML):');
// Process xhr.responseXML (which is already a Document object)
console.log(xhr.responseXML.documentElement.nodeName);
} else {
// Fallback: parse responseText manually if responseXML is null
console.log('Received XML as text, parsing manually...');
try {
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xhr.responseText, "application/xml");
const parseError = xmlDoc.querySelector('parsererror');
if (parseError) {
throw new Error('Parsing error');
}
console.log('Successfully parsed XML from text:');
console.log(xmlDoc.documentElement.nodeName);
} catch (e) {
console.error('Error parsing XML text:', e);
}
}
} else {
// Handle HTTP errors (e.g., 404 Not Found, 500 Server Error)
console.error('Request failed with status:', xhr.status, xhr.statusText);
}
};
// Set up event handler for network errors (e.g., connection refused)
xhr.onerror = function() {
console.error('Network error occurred');
};
// Send the request
xhr.send();
}
// Usage:
loadXmlWithXHR('/api/data.xml'); // Example URL

Key points for XHR:

  • Event-driven: Relies on onload and onerror callbacks.
  • xhr.status: Contains the HTTP status code.
  • xhr.responseXML: If the server sends the correct Content-Type (like application/xml or text/xml), the browser may automatically parse the response into a DOM Document accessible here. This can sometimes be null even with correct XML, so fallback parsing of xhr.responseText is often needed.
  • xhr.responseText: Always contains the response body as a string.

Fetching XML data is used for:

  • Loading configuration or settings files.
  • Retrieving data from legacy systems or SOAP web services.
  • Updating parts of a web page dynamically without a full reload (AJAX - Asynchronous JavaScript and XML, though JSON is more common now for this pattern).
  • Fetching data feeds like RSS or Atom.