Exploring the XML data received through an AJAX request

There is an XML file that I have defined

<?xml version="1.0" encoding="UTF-8"?>
<root>
<town>
   <area>20000</area>
   <population>10000</population>
</town>
</root>

Using AJAX, I load the XML file and attempt to parse it.

<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
 myFunctionParsing(this);
}};

xhttp.open("GET", "towns.xml", false);
xhttp.send();

function myFunctionParsing(xml)
{
  var xmlDoc = xml.responseXML;
  var nodes = xmlDoc.getElementsByTagName("town");   
  var n = nodes[0].childNodes[0];    
  console.log(n.tagName);
  var aDiv = document.getElementById("area");
  aDiv.innerHTML = n.nodeValue;
}

The purpose of this script is to insert the value of the node "area" into a div named "area".

Why am I unable to write this value? Why is n.tagName coming up as undefined?

Answer №1

There are a few key points to consider:

  • I have implemented MDN's tutorial on XMLHttpRequest, demonstrating how to change the mime type to ensure efficient XML parsing without using responseXML.
  • querySelector is highly recommended over getElementsByTagName. It simplifies the code and enhances readability.

function parseXML(xml) {
  
  var area = xml.querySelector('town area');
  console.log(area.textContent); // => 20000

}

var url = 'https://gist.githubusercontent.com/gabrielflorit/c618f26ac367fbaf91846efe73913c23/raw/b3c9c3e8d0f1dc747006103442b3b19bf7c91d9c/town.xml';

var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);

// If specified, responseType should be an empty string or "document"
xhr.responseType = 'document';

// overrideMimeType() can be used for accurate XML parsing
xhr.overrideMimeType('text/xml');

xhr.onload = function () {
  if (xhr.readyState === xhr.DONE) {
    if (xhr.status === 200) {
      parseXML(xhr.response);
    }
  }
};

xhr.send(null);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating through various div elements in Javascript and sending parameters to a script

Context In my project, I am using PHP to generate a series of voting sections. Each section follows the same format except for a unique number assigned to it, which increases with each iteration of the PHP loop. To keep track of the unique numbers, I uti ...

Retrieve the data attribute from a specific dropdown menu using jQuery

Here is the code snippet I am currently working with: $('.tmp-class').change(function() { $('.tmp-class option:selected').each(function() { console.log($('.tmp-class').data('type')); }) ...

What's the best way to retrieve a value from a function that invokes itself multiple times?

My task involves navigating through nested object data to find a specific result. I am using the findByKey function, which recursively calls itself until the desired result is found. However, instead of returning object.source, I am getting undefined. as ...

"Using jQuery to enable ajax autocomplete feature with the ability to populate the same

I am encountering a problem with jQuery autocomplete. It works perfectly fine with one textbox, but when I create multiple textboxes using jQuery with the same ID, it only works for the first textbox and not the others. My question is how can I create mult ...

Recursively removing an item in React components

There is an array containing nested objects that I am working with. My goal is to successfully remove the specific element from this array. Interestingly, when I attempt to delete a non-nested element, everything works fine. However, when I try to remove a ...

Utilizing query parameters and operators for managing collections

When working with GraphQL, what is the optimal approach to designing an "API query language" for filtering collections of items using various operators? For instance, in REST APIs, parameters like /family/people?height="192"&weight[]=">=65"&we ...

Adjust the FlipClock time based on the attribute value

When setting up multiple FlipClock objects on a page, I need to retrieve an attribute from the HTML element. The specific HTML tag for the clock is: <span class="expire-clock" data-expire="2015-09-22"> Is there a way to access '2015-09-22&apos ...

Sending data from a web page to a server using the Ajax

After going through some tutorials, I realized that my script is not working as expected. To address this issue, I am trying to implement the functionality of inserting data into my database using a PHP file named shoutboxform.php. However, since I intend ...

jQuery autocomplete feature fails to retrieve suggestions from local text file

I have implemented the code from a Plunker example in an attempt to minimize the number of ajax requests made to the database. The JSON data is being generated correctly and stored in a text file. However, when I try to display autocomplete options, only ...

reasons why the console is not logging updated states

I'm having trouble logging the updated state values after using setState. The values seem to be updating fine in the render function, but not in the tokenAccess() method. Can anyone explain why this is happening? import React, { Component } from &apo ...

Using onClick function to pass the value of an input textbox in PHP

I have an input text field and I am looking to pass the values entered inside the element through a JavaScript onClick event. <form> <fieldset> <label>Common Site ID: </label><span><?php echo $commonsiteid ?>< ...

Issue encountered while attempting to retrieve a response from CodeIgniter through Ajax code

I need to send a request to CodeIgniter in order to receive a response from my database: $(document).ready(function(){ $('.confirm_send').on('click',function(){ var base = '<?php echo base_url(); ?>'; var confirm_sen ...

Issue with Material UI button not properly redirecting to specified path

Having an issue with a button that should redirect to a specific component with props on click. <Button variant="contained" color="primary" className={classes.button} endIcon={<SendIcon/>} onClick={() => { <Redirect ...

How can I retrieve the value from the input field using vue.js?

I am currently utilizing the vue-js-toggle-button library. While I understand that I can access the value inside the name using $refs, the issue arises as I have 3 toggle buttons and cannot set a Ref because I want to retrieve the name value dynamically i ...

Can you explain the significance of the syntax "require: ^"?

Can someone explain the significance of the ^ symbol under require in this Angular directive code snippet? I came across this code and am having trouble understanding its meaning. .directive('accordionGroupHeading', function() { return { ...

Display a still image in cases where the browser does not support 3D images

I need to display a 3D image in my HTML page if the browser supports canvas, otherwise I want to show a static image. The image should be loaded dynamically when the page loads. <!DOCTYPE html> <html class="no-js" lang="en"> <head> ...

How can I override the default success_url and redirect to a custom page in Stripe Checkout?

QUESTION: I have been experiencing an issue with a webhook in my Node.js application. When the event 'checkout.session.completed' is triggered, the user is automatically redirected to the success_url, regardless of my attempts to redirect them t ...

Exploring different ways to navigate JSON data dynamically and efficiently modify it

I have a JSON data structure resembling a map. var map = { level1 : { x : {name:'level1 x' , }, y : {name:'level1 y'} }, level2 : { x : {name:'level2 x&a ...

What is the method for setting a condition within the setState function?

I used if for the title: in SetConfirmDialog, but it's not working. How can I fix this? <Button color={user.active ? "success" : "error"} variant="text" startIcon={<UserCheck />} title={user.active ? &quo ...

Using Javascript to navigate links in a list using keyboard arrow keys

When links are not wrapped in other elements, I am able to change focus easily. Here is how it works: HTML <a id="first" href="#" class='move'>Link</a> <a href="#" class='move'>Link</a> <a href="#" class=&a ...