Troubleshooting the issue with ajax loadXml callback functionality

My table is empty and I can't figure out where the mistake is. I want to use the console to debug, but I'm not sure how.

Update: I found a working sample here http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_xml2. I used similar code, but with different XML data and it's not working. I don't understand why.

https://i.stack.imgur.com/jYmM6.png

<!DOCTYPE html>
    <html>
    <head>
    <title>XML Data Block Demo</title>

    <style>
    table, th, td {
    border: 1px solid black;
    border-collapse:collapse;
    }
    th, td {
    padding: 5px;
    }
    </style>

    <script>
    function parseXML(input) {
    var xml = input.responseXML;
    var parser = new DOMParser();
    var doc = parser.parseFromString(xml, "application/xml");
    var lineItems = doc.getElementsByTagName("Stock");

    var table="<tr><th>Ticker</th><th>Price</th></tr>";
    for (i = 0; i <lineItems.length; i++) { 
        table += "<tr><td>" +
        lineItems[i].getElementsByTagName("Ticker")[0].childNodes[0].nodeValue +
        "</td><td>" +
        lineItems[i].getElementsByTagName("Price")[0].childNodes[0].nodeValue +
        "</td></tr>";
    }  

    document.getElementById("table").innerHTML = table;
    }

    function loadXML() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
        parseXML(xhttp);
        }
    };
    xhttp.open("GET", "http://localhost/ajax/xml/demo1/stocks.xml", true);
    xhttp.send();
    }
    </script>
    </head>
    <body onload="loadXML()";>
    <table id="table"></table>
    </body>
    </html>

Answer №1

After testing your function with the content of stocks.xml, it seems to work fine except for IE11. I recommend making the following change:

function parseXML(input) {
  var xml = input.responseXML || input.responseText;
  var doc;
  try {
    var parser = new DOMParser();
    doc = parser.parseFromString(xml, "application/xml");
  } catch(err) {
    doc = new ActiveXObject("Microsoft.XMLDOM");
    doc.async = false;
    doc.loadXML(xml);
  }

The full code snippet is shown below:

<!DOCTYPE html>
<html>
<head>
    <title>XML Data Block Demo</title>
    <style>
        table, th, td {
            border: 1px solid black;
            border-collapse:collapse;
        }
        th, td {
            padding: 5px;
        }
    </style>

    // JavaScript code here...

</head>
<body onload="loadXML()";>
<table id="table"></table>
</body>
</html>

And here is the XML content provided:

<?xml version="1.0"?>
<portfolio xmlns:dt="urn:schemas-microsoft-com:datatypes">
    // Stock data here...
</portfolio>

The visual result on Chrome / IE / Firefox latest versions can be viewed at the following link:

https://i.stack.imgur.com/OpcF9.jpg

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

Updating Bootstrap Indicators with jQuery on Click Event

Unfortunately, I am unable to share an image due to limited internet data. My goal is to switch each image to its sprite equivalent. There are three list items that I'm struggling to change because they each have two classes that need to be updated. ...

You are limited to using a maximum of two custom tags within a custom div

I came up with this code that is supposed to style the elements differently based on their tag names. However, when I tested it, the styling did not work as expected. For example, 'London' should be displayed as a large and bold h1 text, while th ...

What is causing these TypeScript type assertions to go unnoticed?

While reviewing type assertions, I noticed something interesting about the last three variable assignments - they don't produce errors. It's perplexing because I thought I was trying to change 'helo' into 'hello', which should ...

Exploring Alternative Methods to Navigate Through Elements Using JQuery UI Autocomplete

After testing two different approaches: <div id = "team-search-container"> <label for="team-search" class = "text-center"> <input type = "text" id = "team-search"> </label> </div> With the following code sni ...

jQuery - Unauthorized request

jQuery v1.7.2 I encountered an error when running a function. The error message displayed was: Uncaught TypeError: Illegal invocation Below is the snippet of the function causing the issue: $('form[name="twp-tool-distance-form"]').on( ...

A step-by-step guide on effectively swapping out every element in an array with its corresponding index location

After pondering over this question and conducting a search to see if it has been asked before, I couldn't quite find the answer due to difficulty in phrasing my inquiry. In case this question has already been addressed, I apologize for any duplication ...

Could you share the most effective method for implementing a live search feature using javascript or jquery?

While attempting to create a live search for a dataset containing over 10,000 rows, I specified the DOM structure that is available. Despite my efforts to check each result after a single input during the live search process, my browser keeps hanging. Is t ...

ajax modal form editing

Encountered an issue with editing a form using modal ajax, where the edit form pops up but the data remains empty. The code snippet for my controller: public function edit() { $id=$this->uri->segment(3); $data=array( 'project' => $th ...

"What is the best way to access the value of a useState variable in ReactJS on a global

Below is my reactJS code snippet - useEffect(()=>{ const getinterviewerDetails= async ()=>{ const data1 = await axios.get("http://localhost:8083/api/GetProduct") .then(response => { console.log("role is " ...

Tips for stopping automatic scrolling (universal solution)

Issue or Inquiry I am seeking a way to disable actual scrolling on an element while still utilizing a scrollbar for convenience (avoiding the need for manual JavaScript implementations instead of relying on browser functions). If anyone has an improved s ...

Activating view loading in AngularJS through child window authentication (OAuth)

I have tried implementing OAuth in AngularJS using Hello.js following what I believe is the best practice. However, I am encountering some issues with my current approach as described below: After injecting Hello.js into Angular and setting up the OAuth p ...

Tips for identifying if the function "res.end()" has been executed or not

Is there a method to determine if the res.end function has been triggered? var http = require('http'); http.createServer(function (req, res) { some_function_may_called_end(req, res); // Is there a way to check for this? if(res.is_ended = ...

I am looking to retrieve a specific input value from a JSON array using JavaScript

I have created an array called 'PROPERTIES' which accepts values like username, password, sid, etc. I am looking to retrieve these entered values using JavaScript. 'PROPERTIES': {'gatewayurl': {'Name': ...

Code coverage analysis in a node.js TypeScript project consistently shows no coverage metrics

I'm currently working on a backend TypeScript project where I'm aiming to obtain coverage reports for unit test cases. However, Jest is returning empty coverage reports both in the terminal and in the HTML report, with no information provided. Ev ...

Leveraging jQuery to delay the processing of AJAX requests

Managing a list of 15+ ajax requests that need to be executed in a specific sequence can be challenging. Each ajax call must wait for the previous one to finish before proceeding. This issue is compounded by the fact that the callback function for each aja ...

Passing ngModel from controller to directive in AngularJS

I'm currently working on a project that involves a controller with an attribute directive nested inside of it. This directive requires access to the ngModel of its parent controller. For more context, feel free to check out this Plunkr. Issue at Han ...

Transforming complex mathematical equations into executable code using the node.js platform

Looking to implement a mathematical formula found at the following link: https://en.wikipedia.org/wiki/Necklace_(combinatorics)#Number_of_bracelets into node.js for calculating the total number of distinct ring sequences that can be created with n length ...

Implement a formatter function to manipulate the JSON data retrieved from a REST API within the BootstrapVue framework

My bootstrap-vue vue.js v2.6 app is receiving JSON data from a REST API. The data structure looks like this: { "fields": [ { "key": "name", "label": "name", & ...

Having trouble loading environment variables in NextJS on Heroku?

I am currently utilizing NextJS and deploying my application on Heroku. When the page initially loads, I am able to retrieve data through getInitialProps without any issues. However, when trying to access this data in a regular function, I encounter an er ...

Switching an :active class using ReactJS

Currently, I am working on creating an onboarding screen where the user is required to select three or more items. Once the user clicks on an item, a purple overlay should remain visible. For reference, this is what I have in mind: Sharing my code snippe ...