Obtaining Data from an XML Node Using AJAX

Trying to extract statistics from my XML based on a specific name request, but encountering issues with my JavaScript functionality.

XML data:

<player> 
<forward><name>Joe</name><stats>45</stats></forward> 
<forward><name>Jack</name><stats>42</stats></forward> 
<forward><name>Peter</name><stats>34</stats></forward> 
<forward><name>Steve</name><stats>21</stats></forward>
<goalie><name>Pat</name><stats>2.34</stats></goalie>
</player> 

HTML setup (ajax):

<html>
<head>
<script language="JavaScript">

function LoadDoc(vValue) {
 xmlhttp = new XMLHttpRequest();
 xmlhttp.open("GET", "player.xml", true);
 xmlhttp.onreadystatechange=function() {
 if (xmlhttp.readyState==4) {
  Answer(xmlhttp.responseXML, vValue);
  }
 }
 xmlhttp.send(null);
}

function Answer(doc, ParamValue) {

var counts=doc.getElementsByTagName("forward");
 for(var i=0;i < counts.length; i++){ 
  alert(counts.length)
  var vname = counts[i].getElementsByTagName('name');
  alert(vname[i].firstChild.nodeValue)
  var vstats = counts[i].getElementsByTagName('stats');
  alert(vstats[i].firstChild.nodeValue);
  if (vname[i].firstChild.nodeValue == ParamValue)
  {
        alert(stats[i].firstChild.nodeValue);
  }
 }

}
</script>
</head> 
<body> 
<form> 
<input type="field" id="champ" /> 
<input type="button" onclick="javascript:LoadDoc(document.getElementById('champ').value);" /> 
</form> 
</body> 
</html> 

The first ALERT correctly identifies 4 elements
The second ALERT successfully displays 'JOE'
The third ALERT correctly shows '45' (the stats of the first forward)

However, the alerts are only triggered once... Why isn't it looping 4 times as expected? Any insights on what might be causing this issue? Is there a better approach to retrieve the statistics?

Answer №1

Make sure to check the console for error messages. Upon initial inspection, it appears that the code

alert(stats[i].firstChild.nodeValue);
is trying to access a variable called stats which has not been declared. If this line of code is executed, it will likely trigger a ReferenceError and stop the script from running, resulting in the alerts being displayed only once.

Answer №2

Many thanks to Dagg Nabbit for helping me locate the solution. After identifying the error, it appears that the vname[i] variable was non-existent. To remedy this, I substituted "i" with "0" resulting in vname[0]. Rather than targeting the second element named "name", I focused on the first. By swapping out vstats[i] with vstat[0], everything now functions flawlessly.

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

Steps for transferring an `<li>` element from one `<ul>` to another

<ul id="List"> <li class="li">1</li> <li class="li">2</li> </ul> <ul id="List2"></ul> const items = document.querySelectorAll(".li"); for(var i = 0; i < ...

Library package for Selenium web driver

I'm new to using Selenium web driver As I started writing my code, an error occurred in the first line. The package is showing as not accessible." Any assistance would be greatly appreciated. https://i.sstatic.net/vYUmS.png ...

Issue: Compilation unsuccessful due to an error in the Babel loader module (./node_modules/babel-loader/lib/index.js). Syntax error

I'm currently exploring how to integrate the Google Maps Javascript API into my VueJs project without relying on the vue2-google-maps package (as it seems too restrictive to me). Here's what I've done so far, after registering my Vue compon ...

Is it feasible to style individual letters in a word within an input field?

Is it possible to change the styling of individual letters in an input containing text? For example, if the word 'Test' is in the input, can I make the 'Te' bold while leaving the 'st' regular? Alternatively, perhaps I'd ...

Troubleshooting collapsing problems in Bootstrap 5.2 using Webpack and JavaScript

I am currently developing a project utilizing HTML, SASS, and JS with Webpack 5.74.0. My goal is to implement a collapsible feature using Bootstrap 5, however, I ran into some issues while trying to make it work. To troubleshoot, I attempted to direct ...

Enabling automatic scaling during the rendering of an .stl file using three.js

I'm in the process of developing a server/webpage with the following functionality: Users can upload an .stl file to be 3D-printed The server executes a mesh repair script on the uploaded .stl file The corrected .stl file is displayed in the user&ap ...

NodeJS sqs-consumer continuously triggers the function to execute

I have been utilizing the npm package called sqs-consumer to monitor messages in a queue. Upon receiving a new message, I aim to generate a subfolder within an S3 bucket. However, I am encountering a problem where even after the message is processed and re ...

Struggling to troubleshoot an error - Invalid key Token '{' found at column 2

I am encountering a debugging issue that I can't seem to resolve. form-field.html <div class='row form-group' ng-form="{{field}}" ng-class="{ 'has-error': {{field}}.$dirty && {{field}}.$invalid }"> <label cla ...

An improved solution for avoiding repetitive typeof checks when accessing nested properties in the DOM

One common issue I encounter when working with nested DOM objects is the risk of undefined errors. To address this, I often use a conditional check like the one shown below: if("undefined" != typeof parent && "undefined" != typeof parent.main ...

What is the best way to empty an array within the state of a React component using JSX?

I need assistance with a React and JSX project where I am creating input fields that can be removed by clicking a button. Currently, I have an empty array stored in the state of the Page component. This array is updated using the addItems function. Howev ...

Tips on sending custom SOAP headers to Python SUDS which are not specified in the WSDL document

I am currently facing an issue with connecting my network camera using suds. It appears that suds is not sending all the required information to establish a successful connection. I need to add additional soap headers that are not included in the WSDL file ...

capturing webpage content with javascript for use in a screenshot

Is there a way to capture a screenshot of a webpage using JavaScript and utilize the canvas tag for this purpose? I attempted to use the html2canvas plugin in the past, but found it lacking in power. I would like to achieve this without relying on extern ...

Encountering an error when importing chart.js-plugins-annotations

import { annotation, Chart, defaults } from 'chart.js'; An issue arises when using this import statement: localhost/:1 Uncaught TypeError: Failed to resolve module specifier "chart.js". Relative references must start with either &quo ...

Does the gltf loader in three.js have compatibility issues with Internet Explorer 11?

Despite the claims on the official website that gltf files should load in three.js scenes using IE11, I have been experiencing issues with the loader. Even the examples provided by three.js fail to work on Internet Explorer when it comes to loading gltf fi ...

Mastering the art of using the async pipe in conjunction with rxjs

I require assistance as the loading component of my async pipe does not activate, despite the data loading correctly. The loading template fails to trigger during subscription even though I am using a BehaviorSubject in my service. I have attempted various ...

Improve Email Regular Expression to Restrict Consecutive Periods

I'm not very good with regular expressions, so I decided to seek some help. Here's the regular expression I have: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.) ...

List application now includes the capability of adding three items in one go, rather than just one

Furthermore, when the script is placed in the same file as the html, it results in the addition of two items simultaneously instead of three. var itemNum = 1; $("document").ready(function() { $("#addCL").click(function() { var itemId ...

Enhancing Struts2 JSON Plugin: Including ActionMessages, ActionErrors, and FieldErrors in the response

While working on my jQuery Ajax posts, I want to include any actionmessages, actionerrors, and fielderrors in the response (in JSON format). Here is what I added: <result name="input" type="json"> <param name="ignoreHierarchy">false&l ...

Exploring the World of Browserify Submodules

/xyz /abc.js /abcdef.js /index.js When working with node.js, if you use the require statement for a directory (require('xyz')), it will automatically search for an index.js file within that directory and return the exports defined in that ...

Issues with concealing the side menu bar in Vue.js

I've been attempting to conceal the side menu bar, with the exception of the hamburger icon when in the "expanded" state. Despite my efforts to modify the CSS code, I am still struggling to hide the small side menu bar. The following images represent ...