Sling Academy
Home/JavaScript/Handle XML and JSON Responses via JavaScript XMLHttpRequest

Handle XML and JSON Responses via JavaScript XMLHttpRequest

Last updated: December 14, 2024

Handling XML and JSON responses using JavaScript's XMLHttpRequest is an essential skill for developers who work with APIs and web services. This article will guide you through the process of issuing requests to fetch or submit data and parsing the responses in both XML and JSON formats with examples for better understanding.

Introduction to XMLHttpRequest

XMLHttpRequest is a built-in browser object that enables you to make HTTP requests in JavaScript to fetch resources from a server. It can be used with other operations such as POST, PUT, DELETE besides the usual GET. When using XMLHttpRequest, you handle the server's response in various formats, the most common being XML and JSON.

// Basic initialization of XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);

Handling XML Responses

XML (eXtensible Markup Language) is a markup language commonly used to transport and store data. Let's see how to fetch and parse XML responses:

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) { // Request successful
    var xmlDocument = xhr.responseXML; // Retrieve the XML document
    var items = xmlDocument.getElementsByTagName("item");
    for (var i = 0; i < items.length; i++) {
      console.log(items[i].textContent);
    }
  }
};

xhr.open("GET", "https://api.example.com/data.xml", true);
xhr.send();

In this example, once the request is ready and successful, we use responseXML to obtain the XML data and parse it with methods such as getElementsByTagName.

Handling JSON Responses

JSON (JavaScript Object Notation) is a lightweight format that is easily readable and regularly used with JavaScript. Here’s how you can handle JSON responses:

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) { // Request successful
    var jsonResponse = JSON.parse(xhr.responseText); // Parse JSON string into object
    jsonResponse.forEach(item => {
      console.log(item.name);
    });
  }
};

xhr.open("GET", "https://api.example.com/data.json", true);
xhr.send();

Here, after successfully receiving the response, the data is accessed through xhr.response or xhr.responseText in string format, which you can parse to a JSON object with JSON.parse.

Comparing XML vs JSON

Choosing between XML and JSON often depends on requirements:

  • Readability: JSON is generally more readable, especially for humans.
  • Data Size: JSON tends to be more compact compared to XML.
  • Complexity: XML can represent more complex data structures like attributes and mixed content.
  • Tool Support: JSON is supported directly in JavaScript, while XML requires additional parsing.

Conclusion

The XMLHttpRequest object allows for a powerful and flexible way to communicate with web servers either with predefined data structures like XML or adaptable ones like JSON. Being proficient in handling both types of responses expands the integration and operation possibilities within web applications. When implementing API interactions, always consider the type of data you'll work with, choose the appropriate data format, and use synchronous or asynchronous requests based on the app's needs.

Next Article: Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript

Previous Article: Make AJAX Requests with XMLHttpRequest in JavaScript

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration
  • Integrate Accessibility Features via the WebVTT API in JavaScript