Having trouble parsing XML with JavaScript

I am currently attempting to parse an XML file using JavaScript for a school assignment, and I am required to use pure JavaScript without jQuery. I am able to retrieve one value successfully, but encountering issues with another.

The problem lies within my JavaScript code responsible for extracting values from the XML file. Specifically, while I can successfully fetch the startLng value, the program returns startLat as undefined even though it is clearly defined in the XML file. I am unable to identify the root cause of this issue.

My objective is to extract both LatitudeDegrees and LongitudeDegrees from the XML file. However, the current implementation only retrieves LongitudeDegrees successfully, leaving LatitudeDegrees as undefined. What mistake could I possibly be making?

function loadXMLDoc() {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      getLatLang(xmlhttp);
    }
  };
  xmlhttp.open("GET", "G1.TCX", true);
  xmlhttp.send();
}

function getLatLang(xml) {
      var xmlDoc = xml.responseXML;
      var x = xmlDoc.getElementsByTagName("Trackpoint");
      startLat = x[0].getElementsByTagName("Position")[0].getElementsByTagName("LatitudeDegrees")[0].childNodes[0].nodeValue;
      startLng = x[0].getElementsByTagName("Position")[0].getElementsByTagName("LongitudeDegrees")[0].childNodes[0].nodeValue;  
}

Below is a snippet from the XML file:

<Trackpoint>
    <Time>2008-10-28T15:58:22Z</Time>
    <Position>
      <LatitudeDegrees>59.4111992</LatitudeDegrees>
      <LongitudeDegrees>13.5304104</LongitudeDegrees>
    </Position>
    <AltitudeMeters>85.6945801</AltitudeMeters>
    <DistanceMeters>0.2149343</DistanceMeters>
    <HeartRateBpm xsi:type="HeartRateInBeatsPerMinute_t">
      <Value>116</Value>
    </HeartRateBpm>
    <SensorState>Absent</SensorState>
    <Extensions>
      <TPX xmlns="http://www.garmin.com/xmlschemas/ActivityExtension/v2" CadenceSensor="Footpod"/>
    </Extensions>
  </Trackpoint>

Answer №1

Issue successfully resolved.

The main issue was the absence of a document load event.

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

Limit the jQuery dialogue button to just one click

My goal is to create a jQuery dialogue box that sends data when the 'OK' button is clicked. The challenge I'm facing is making sure it only sends the data once, regardless of how many times the button is clicked. $.dialogue({ ...

JavaScript - Need to automatically scroll to a different div when scrolling occurs

Currently, my focus is on creating a single-page website where the main content is displayed in large boxes arranged vertically down the page. If you have any suggestions or thoughts on using JavaScript to navigate to each content box more efficiently, I ...

Symfony: Enhancing array elements with updated bootstrap progress bar

I'm facing a challenging issue that I need help with. Currently, I have a command set up to send a large number of emails (around 300 or more) every 5 minutes using cron in order to distribute a newsletter. My goal is to keep track of how many emails ...

Implementing popup alert for multiple tabs when Javascript session times out

I have implemented javascript setInterval() to monitor user idle time and display a popup alert prior to automatic logout. However, it seems to be functioning correctly only in single tabs. Here is the code snippet: localStorage.removeItem("idleTimeValue ...

Solving synchronization issues when updating and selecting MySql data in a Node.js environment with concurrent multiple requests

Currently, I'm using expressJS with an endpoint that connects to a MYSQL database. This endpoint executes a query to retrieve data and assigns the first result to a user by updating a specific field with the user ID. The rule is that each row can onl ...

Using Angular 4 to import an HTML file

I am trying to save test.svg in a component variable 'a' or svgicon.component.html. To achieve this, I have created the svgicon.component.ts file. However, it's not working. What steps should I take next? svgicon.component.ts import ...

Assistance Required in Turning Down Trade Requests on Steam That Involve Losing items

Currently, I have a code snippet from a Steam bot that processes incoming trade offers by accepting or declining them based on their state. However, my goal is to modify it in a way so that it automatically accepts trade offers where I receive items, but ...

What is the proper way to designate a manifest.json link tag on a limited-access website controlled by Apache shibboleth?

The issue arises when attempting to access the manifest.json file. It has been declared as follows: <link href="manifest.json" rel="manifest"/> Is it possible to declare the manifest tag inline, or what would be the most effective way to declare it ...

Exploring the angular js repeater component's context menu options

In one of my current projects, the client has specifically requested a right-click menu feature. However, the challenge lies in ensuring that the function triggered by the menu options has access to relevant information from the model. For instance, you ...

How to resolve the error of "Objects are not valid as a React child" in NextJs when encountering an object with keys {children}

I am currently working on a nextjs application and I have encountered an issue with the getStaticPaths function. Within the pages folder, there is a file named [slug].tsx which contains the following code: import { Image } from "react-datocms"; i ...

How can I display two slides at once in Ionic 2/3 on a wide screen?

I have been searching for a solution that will allow me to display 1 ion-slide if the device screen is small, but if it's larger, then I want to display 2 ion-slides. Unfortunately, I have not been able to find a suitable solution yet. As an example, ...

Tips on combining $scope object values within AngularJS

I am extracting data from various SharePoint pages lists by utilizing a Factory. Within my code, I am determining the number of items with a "Completed" status in each list. I am attempting to store these values in an array, but it consistently returns ...

Creating an HTML5 video tag with bearer authentication using a WebAPI: The ultimate guide

My ASP.NET WebAPI requires bearer authentication, and most of my requests towards the API follow this format: GET http://localhost:29080/api/v1/users/me HTTP/1.1 Host: localhost:29080 Connection: keep-alive Accept: application/json, text/plain, */* Origin ...

JavaScript For/in loop malfunctioning - Issue with undefined object property bug

Currently, I am tackling a basic For/in loop exercise as part of a course curriculum I am enrolled in. The exercise involves working with a simple object containing 3 properties and creating a function that takes two parameters - the object name and the it ...

Guide for extracting the first matching group with regex in node.js

Extracting a specific value from a string in a text file can be tricky. In the example below, the goal is to get the value of valuetext: <CONFIG_entry name="Konfiguration:Allgemeine Einstellungen:CMS-Server:Port" valuetext="15000" value="15000" adr="CL ...

Auth0 and Vue.js work together seamlessly to easily redirect users back to their previous page

I have integrated auth0 into my Vue.js application for handling logins. Within my AuthService, I manage all the auth0 operations. In the constructor, I instantiate a new auth0 object and set the default redirectUrl to the desired location: import auth0 f ...

What is another option for toggling in jQuery?

After deprecating the toggle method, I found a new way to toggle div: $("#syndicates_showmore").on("click", function () { if (!clicked) { $('#syndicates').fadeTo('slow', 0.3, function () { $(this).css( ...

The overflow property is set to scroll in jQuery, causing continuous scrolling until reaching a certain point, at which it

Continuously adding new chat messages will show the latest one, but eventually it stops scrolling down automatically. How do I resolve this issue? Thank you. http://jsfiddle.net/VMcsU/ $("#button1").click(function(){ $("<div>").html("text").app ...

Mapping Longitude and Latitude with TopoJSON and D3

Currently utilizing the UK Geo JSON found at this link to generate a UK SVG Map. The goal is to plot longitude and latitude points onto this map. The GeometryCollection place is being added to the map in the following manner: data.objects.places = { ...

Guide to changing text value for translation with api

I'm interested in creating an application that can translate English text into Yodish, but I'm struggling with indicating the value of my text box. Currently, I'm attempting to access the data text properties. While I've been able to r ...