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

Performing an asynchronous Ajax call from a partial view in an Asp.net MVC application

Is it possible to use Ajax to fetch data from a form located in a partial view, send it to a controller, and receive a response message? Utilizing Ajax $("#submitContactInfo").on("click", function () { if ($('#contact-form').valid() === true) { ...

Concealed Input Enhancements for AutoComplete

Hey there! I'm new to AJAX and could really use some help with my autocomplete function. I'm trying to store the ID of the user's selection in a hidden input field, but I've hit a roadblock. So far, my function isn't working as exp ...

Tips for Guaranteeing a Distinct Email and Username are Stored in MongoDB with Mongoose

db.UserSchema = new db.Schema({ user: {type:String, unique:true, required:true,index:true}, email: {type:String, unique:true, required:true,index:true}, password: {type:String, required:true}, phon ...

Is it possible for a prop to change dynamically?

I am currently developing a component that is responsible for receiving data through a prop, making modifications to that data, and then emitting it back to the parent (as well as watching for changes). Is it possible for a prop to be reactive? If not, wh ...

Having trouble getting sweet alert to work with my PHP script

I’m integrating Sweet Alerts 2 into my webpage in order to prompt the user when trying to delete something. However, I'm encountering an issue where the PHP file is not being triggered when the user presses delete and the Sweet Alert does not appear ...

Moving a Node project to a different computer

I am looking to transfer my Angular project from a Windows machine to a Mac. I attempted to copy the folder and run npm install, but encountered an issue. Here is the error message I received: sh: /Users/pawelmeller/Documents/hotel/angular4/node_modules/ ...

Leveraging several AJAX requests for a single element in Bootsfaces

Is it possible to achieve the following: <b:navLink ... onclick="ajax:callBeanMethodA;ajax:callBeanMethodB" /> I have tried but it doesn't seem to work. Is there a way to make it work? Thank you ...

When comments are submitted via AJAX, they are displayed twice, but upon reloading the page, they only appear once

After using the codes below to add a comment to a post and display it without refreshing the page, I encountered an issue where the comment is displayed twice instead of once. However, the comment is only saved once in the database. Interestingly, when the ...

Guide on utilizing multiple ng-apps alongside multiple controllers

Having trouble accessing controller values in different ng-apps? Here's a setup with two ng-apps and their controllers, where you may encounter errors when trying to access the value of one controller in another. Need some assistance with this issue. ...

What is the method to permanently install and enforce the latest version using npm?

We are implementing a private npm module for exclusive use within our organization. Given that the module is managed internally, we have confidence in version updates and changes. Is there a way to seamlessly install this module across multiple projects s ...

Implementing Batch File Uploads using Typescript

Is there a way to upload multiple files in TypeScript without using React or Angular, but by utilizing an interface and getter and setter in a class? So far I have this for single file upload: <input name="myfile" type="file" multi ...

Determine the overall width of a JSX element

Is there a way to retrieve the width of a JSX.Element? In a traditional setup, I would typically use something like: const button = document.createElement('button'); document.body.appendChild(button) window.getComputedStyle(button).width However ...

Tips for updating the pagination layout in Material UI Table

Currently, I am attempting to modify the background color of the list that displays the number of rows in MUI TablePagination. <TablePagination style={{ color: "#b5b8c4", fontSize: "14px" }} classes={{selectIcon: ...

Altering content using jQuery

Trying to create a dynamic quiz using HTML, CSS, and jQuery. I am having trouble changing the <p id=question></P> element with jQuery code as nothing happens. Below is my HTML and jQuery code: <!DOCTYPE html> <html lang='es' ...

Prevent altering client values via developer tools

Our application is built using HTML5, the Foundation framework by ZURB, and AngularJS. We are seeking a way to prevent users from accessing and changing the values of our Angular objects (specifically scope variables) through the developer tool console. ...

JavaScript alert causing disruption to Ajax requests

Currently, I am utilizing JQuery Ajax to retrieve a script from the server. $.ajax({ url: src, type: "GET", dataType: "script", timeout: transaction_timeout }).done(function(){}) .fail(function() { alert("Error in server");}) .always(funct ...

HTML Navigator encountering Javascript Anomaly

Here is the code snippet I'm working with: driver = new HtmlUnitDriver(); ((HtmlUnitDriver) driver).setJavascriptEnabled(true); baseUrl = "http://www.url.com/"; driver.get(baseUrl + "/"); ... However, whenever I ...

Align Horizontal Fixed Element

<html> <head> <style> #rectangle { position: absolute; right: 0; bottom: 0; width: 150px; height: 200px; } </st ...

How can you incorporate a custom button into the controlBar on videoJS in responsive mode?

The video player I have created using videoJS includes custom buttons in the control bar. These buttons are not clickable when viewed on mobile or tablet devices without forcing them to work. let myButton = player?.controlBar.addChild('button'); ...

React - Refreshing a component with the help of another component

I've created a NavBar component that contains a list of links generated dynamically. These links are fetched from the backend based on specific categories and are stored within a child component of NavBar named DrawerMenu. The NavBar itself is a chil ...