XML HttpRequest

Loading XML data from servers using AJAX

📡 What is XMLHttpRequest?

XMLHttpRequest is a JavaScript object that enables asynchronous communication with servers. It allows you to load XML data from external files or APIs without refreshing the entire web page.


// Basic XMLHttpRequest
const xhr = new XMLHttpRequest();
xhr.open("GET", "data.xml", true);
xhr.send();
                                    

Purpose:

Fetch XML data from servers dynamically for AJAX applications.

Key XMLHttpRequest Concepts

🔧

Create

Initialize XMLHttpRequest object

const xhr = new XMLHttpRequest();
🚀

Open

Configure the request

xhr.open("GET", "file.xml", true);
📤

Send

Send request to server

xhr.send();
📥

Response

Handle server response

xhr.onload = function() {
  console.log(xhr.responseXML);
}

🔹 Basic XMLHttpRequest Example

Here's a complete example showing how to load XML data from a file and display it on a web page using XMLHttpRequest.

<!DOCTYPE html>
<html>
<body>

<h2>Load XML Data</h2>
<button onclick="loadXML()">Get XML Data</button>
<div id="result"></div>

<script>
function loadXML() {
    // Create XMLHttpRequest object
    const xhr = new XMLHttpRequest();
    
    // Configure request
    xhr.open("GET", "books.xml", true);
    
    // Handle response
    xhr.onload = function() {
        if (xhr.status === 200) {
            // Parse XML response
            const xmlDoc = xhr.responseXML;
            const books = xmlDoc.getElementsByTagName("book");
            
            let output = "<h3>Books:</h3>";
            for (let i = 0; i < books.length; i++) {
                const title = books[i].getElementsByTagName("title")[0].textContent;
                output += "<p>" + title + "</p>";
            }
            
            document.getElementById("result").innerHTML = output;
        }
    };
    
    // Send request
    xhr.send();
}
</script>

</body>
</html>

Result:

Clicking the button loads and displays XML data without page refresh.

🔹 XMLHttpRequest Properties

XMLHttpRequest provides several important properties to monitor and control the request process and access response data.

Common Properties:

  • readyState: Current state of the request (0-4)
  • status: HTTP status code (200, 404, etc.)
  • statusText: Status message ("OK", "Not Found")
  • responseXML: Response as XML document
  • responseText: Response as text string
const xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
    console.log("Ready State: " + xhr.readyState);
    
    if (xhr.readyState === 4) {  // Request complete
        if (xhr.status === 200) {  // Success
            console.log("Status: " + xhr.status);
            console.log("Status Text: " + xhr.statusText);
            
            // Access XML response
            const xmlDoc = xhr.responseXML;
            console.log(xmlDoc);
        }
    }
};

xhr.open("GET", "data.xml", true);
xhr.send();

🔹 Ready States Explained

The readyState property tracks the progress of your XMLHttpRequest. Understanding these states helps you handle requests properly.

xhr.onreadystatechange = function() {
    switch(xhr.readyState) {
        case 0:
            console.log("Request not initialized");
            break;
        case 1:
            console.log("Server connection established");
            break;
        case 2:
            console.log("Request received");
            break;
        case 3:
            console.log("Processing request");
            break;
        case 4:
            console.log("Request finished, response ready");
            // Process the response here
            if (xhr.status === 200) {
                const xmlDoc = xhr.responseXML;
                // Use the XML data
            }
            break;
    }
};

Best Practice:

Always check both readyState === 4 and status === 200 before processing the response.

🔹 Error Handling

Proper error handling ensures your application responds gracefully when requests fail due to network issues or server errors.

function loadXMLWithErrorHandling() {
    const xhr = new XMLHttpRequest();
    
    xhr.open("GET", "data.xml", true);
    
    // Success handler
    xhr.onload = function() {
        if (xhr.status === 200) {
            const xmlDoc = xhr.responseXML;
            console.log("XML loaded successfully");
            // Process XML
        } else {
            console.error("Error: " + xhr.status + " " + xhr.statusText);
        }
    };
    
    // Error handler
    xhr.onerror = function() {
        console.error("Network error occurred");
    };
    
    // Timeout handler
    xhr.ontimeout = function() {
        console.error("Request timed out");
    };
    
    // Set timeout (5 seconds)
    xhr.timeout = 5000;
    
    xhr.send();
}

🔹 Modern Alternative: Fetch API

The Fetch API is a modern alternative to XMLHttpRequest with a cleaner syntax using Promises. It's recommended for new projects.

// Using Fetch API to load XML
async function loadXMLWithFetch() {
    try {
        const response = await fetch('data.xml');
        
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        
        const text = await response.text();
        const parser = new DOMParser();
        const xmlDoc = parser.parseFromString(text, "text/xml");
        
        // Process XML
        const items = xmlDoc.getElementsByTagName("item");
        console.log("Found " + items.length + " items");
        
    } catch (error) {
        console.error("Error loading XML:", error);
    }
}

// Call the function
loadXMLWithFetch();

Advantage:

Fetch API uses Promises, making code cleaner and easier to read with async/await.

🧠 Test Your Knowledge

Which readyState value indicates the request is complete?