Javascript array not displayed in HTML table - javascript

I am trying to loop through arrays of data which then displayed in the html table. I am able to create a new object and pass the data in the object to an empty array. However, the problem that I am facing right now is that the arrays data is not showing in the table. At the same time, there are no errors shown in the console. I checked all info in the function addToHTML() and it supposed to be correct.I have no idea what I did wrong ? The following are the javascript and html code :
// Main Book object model
function Book(title, author, pages, read) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = read;
}
// Library object model
function Library() {
this.myLibrary = [];
this.addToLibrary = function(myLibrary) {
this.myLibrary.push(myLibrary);
}
}
// Create new book object
let book1 = new Book('Awaken the Giant Within', 'Tony Robbins', '351', 'already read');
let book2 = new Book('Think and Grow Rich', 'Napoleon Hill', '271', 'currently reading');
let book3 = new Book('Rich Dad Poor Dad', 'Robert T. Kiyosaki', '289', 'finish read');
// Create new library object
let library = new Library();
// Add books to the empty array
library.addToLibrary(book1);
library.addToLibrary(book2);
library.addToLibrary(book3);
// Function to add main Book to HTML content
function addToHTML() {
for (let i=0; i < library.myLibrary.length ; i++ ) {
let dataContainer = document.querySelector('#dataContainer');
let titleColumn = document.getElementById('title');
let authorColumn = document.getElementById('author');
let pagesColumn = document.getElementById('pages');
let readColumn = document.getElementById('read');
let book_title = library.myLibrary[i].titleColumn;
let book_author = library.myLibrary[i].authorColumn;
let book_pages = library.myLibrary[i].pagesColumn;
let book_read = library.myLibrary[i].readColumn;
titleColumn.textContent = book_title;
authorColumn.textContent = book_author;
pagesColumn.textContent = book_pages;
readColumn.textContent = book_read;
dataContainer.appendChild(titleColumn);
dataContainer.appendChild(authorColumn);
dataContainer.appendChild(pagesColumn);
dataContainer.appendChild(readColumn);
}
}
console.log(library.myLibrary);
addToHTML();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Book Object</title>
</head>
<body>
<h1>Book template</h1>
<form>
<table id="book-table">
<thead>
<tr>
<th> Title </th>
<th> Author </th>
<th> Pages </th>
<th> Read </th>
</tr>
</thead>
<tbody>
<tr id="dataContainer">
<td id="title"></td>
<td id="author"></td>
<td id="pages"></td>
<td id="read"></td>
</tr>
</tbody>
</table>
</form>
<script src="script.js"></script>
</body>
</html>

Needed to change the HTML + js code
// Main Book object model
function Book(title, author, pages, read) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = read;
}
// Library object model
function Library() {
this.myLibrary = [];
this.addToLibrary = function(myLibrary) {
this.myLibrary.push(myLibrary);
}
}
// Create new book object
let book1 = new Book('Awaken the Giant Within', 'Tony Robbins', '351', 'already read');
let book2 = new Book('Think and Grow Rich', 'Napoleon Hill', '271', 'currently reading');
let book3 = new Book('Rich Dad Poor Dad', 'Robert T. Kiyosaki', '289', 'finish read');
// Create new library object
let library = new Library();
// Add books to the empty array
library.addToLibrary(book1);
library.addToLibrary(book2);
library.addToLibrary(book3);
// Function to add main Book to HTML content
function addToHTML() {
for (let i=0; i < library.myLibrary.length ; i++ ) {
console.log(library.myLibrary)
let tbody = document.querySelector('#tbdy');
let content = `
<tr>
<td id="title">${library.myLibrary[i].title}</td>
<td id="author">${library.myLibrary[i].author}</td>
<td id="pages">${library.myLibrary[i].pages}</td>
<td id="read">${library.myLibrary[i].read}</td>
</tr>`
tbody.innerHTML += content;
}
}
console.log(library.myLibrary);
addToHTML();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Book Object</title>
</head>
<body>
<h1>Book template</h1>
<form>
<table id="book-table">
<thead>
<tr>
<th> Title </th>
<th> Author </th>
<th> Pages </th>
<th> Read </th>
</tr>
</thead>
<tbody id="tbdy">
<tr id="dataContainer">
<td id="title"></td>
<td id="author"></td>
<td id="pages"></td>
<td id="read"></td>
</tr>
</tbody>
</table>
</form>
<script src="script.js"></script>
</body>
</html>

Related

Firebase says initializeApp is not defined after adding libraries

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>List</title>
</head>
<body>
<table>
<thead>
<th>Name</th>
<th>Email</th>
<th>Message</th>
</thead>
<tbody id="tbody1">
</tbody>
</table>
<script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.5/firebase-database.js"></script>
<script id="MainScript">
//-----------Config------------//
var firebaseConfig = {
apiKey: "----------------------",
authDomain: "-firebaseapp.com",
databaseURL: -.firebaseio.com",
projectId: "-9677d",
storageBucket: "--.appspot.com",
messagingSenderId: "-------3",
appId: "------------------------"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
//----------Getting-The-Data-------------------//
function SelectAllData() {
firebase.database().ref('People').on('value',
function(AllRecords){
AllRecords.forEach(
function(CurrentRecord){
var name = CurrentRecord.val().Name;
var email = CurrentRecord.val().Email;
var message = CurrentRecord.val().Message;
AddItemsToTable(name,email,message);
}
);
});
}
window.onload = SelectAllData;
//----------Filling-The-Table-----------------//
var stdNo = 0;
var tbody = document.getElementById('tbody1');
function AddItemsToTable(Name,Email,Message) {
var trow = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
var td4 = document.createElement('td');
td1.innerHTML= sdtNo;
td1.innerHTML= Name;
td1.innerHTML= Email;
td4.innerHTML= Message;
trow.appendChild(td1);
trow.appendChild(td2);
trow.appendChild(td3);
tbody.appendChild(trow);
}
function AddAllItemsToTable(Name){
stdNo=0;
tbody.innerHTML="";
Name.forEach(element => {
AddItemToTable(element.Name, element.Email, element.Message)
});
}
</script>
</body>
This is my code. Above I censored my firebase config. Whenever I run this, it says stdNo is not defined. I am trying to display data from my firebase database into a table. My firebase database looks like this! My Firebase Database Setup
I have tried countless tutorials but none are helping. I always get this error.
Uncaught ReferenceError: sdtNo is not defined
at AddItemsToTable (LIST.php:65:20)
at LIST.php:50:11
at DataSnapshot.ts:148:14
at ke.inorderTraversal (SortedMap.ts:229:9)
at We.inorderTraversal (SortedMap.ts:755:23)
at Je.forEachChild (ChildrenNode.ts:350:29)
at cn.forEach (DataSnapshot.ts:147:27)
at LIST.php:45:18
at EventRegistration.ts:133:12
at Nt (util.ts:588:5)

Fetching data to table row and table column

I'm trying to fetch data from an api.
So far I have tried to fetch data using an api. I have been using this website: https://www.geeksforgeeks.org/how-to-use-the-javascript-fetch-api-to-get-data/
It currently console.logs my array but it does not show up in the table rows that i have created.
I think i might have created the rows wrong in my html, but i cant figure how they should have been set up otherwise. Please show a small example or what to google if that is what is wrong.
The current error message i get is
Uncaught (in promise) TypeError: data.list is not iterable
at show (news.js:37:21)
at getapi (news.js:17:2)
My javascript looks like this:
// api url
const api_url =
"https:newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=xxxxxxxxx";
// Defining async function
async function getapi(url) {
// Storing response
const response = await fetch(url);
// Storing data in form of JSON
var data = await response.json();
console.log(data);
if (response) {
hideloader();
}
show(data);
}
// Calling that async function
getapi(api_url);
// Function to hide the loader
function hideloader() {
document.getElementById('loading').style.display = 'none';
}
// Function to define innerHTML for HTML table
function show(data) {
let tab =
`<tr>
<th>Author</th>
<th>Title</th>
<th>Description</th>
<th>Url</th>
</tr>`;
// Loop to access all rows
for (let r of data.list) {
tab += `<tr>
<td>${r.author}</td>
<td>${r.title}</td>
<td>${r.description}</td>
<td>${r.url}</td>
</tr>`;
}
// Setting innerHTML as tab variable
document.getElementById("news").innerHTML = tab;
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="news.js"></script>
<link rel="stylesheet" href="test.css" />
<meta charset="UTF-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<!-- Here a loader is created which
loads till response comes -->
<div class="d-flex justify-content-center">
<div class="spinner-border"
role="status" id="loading">
<span class="sr-only">Loading...</span>
</div>
</div>
<h1>News</h1>
<!-- table for showing data -->
<table id="news"></table>
</body>
</html>
You need to handle the response correctly.
Working example:
// api url
const api_url = 'https://jsonplaceholder.typicode.com/comments';
// Defining async function
async function getapi(url) {
await fetch(url)
.then((response) => response.json())
.then((data) => {
console.log(data)
hideloader();
show(data)
});
}
// Calling that async function
getapi(api_url);
// Function to hide the loader
function hideloader() {
document.getElementById('loading').style.display = 'none';
}
// Function to define innerHTML for HTML table
function show(data) {
let tab =
`<tr>
<th>id</th>
<th>Name</th>
<th>Body</th>
<th>Email</th>
</tr>`;
// Loop to access all rows
for (let r of data) {
tab += `<tr>
<td>${r.id}</td>
<td>${r.name}</td>
<td>${r.body}</td>
<td>${r.email}</td>
</tr>`;
}
// Setting innerHTML as tab variable
document.getElementById("news").innerHTML = tab;
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="news.js"></script>
<link rel="stylesheet" href="test.css" />
<meta charset="UTF-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<!-- Here a loader is created which
loads till response comes -->
<div class="d-flex justify-content-center">
<div class="spinner-border"
role="status" id="loading">
<span class="sr-only">Loading...</span>
</div>
</div>
<h1>News</h1>
<!-- table for showing data -->
<table id="news"></table>
</body>
</html>
This is what i ended up doing
const url = "xxxxxxx"
fetch(url)
.then((response) => response.json())
.then((data) => {
console.log(data)
let title = document.getElementById("title");
title.innerText = data.articles[0].title;
let title1 = document.getElementById("title1");
title1.innerText = data.articles[1].title;
let title2 = document.getElementById("title2");
title2.innerText = data.articles[2].title;
let title3 = document.getElementById("title3");
title3.innerText = data.articles[3].title;
let title4 = document.getElementById("title4");
title4.innerText = data.articles[4].title;
let title5 = document.getElementById("title5");
title5.innerText = data.articles[5].title;
});
And then just a p tag looking like this:
<p id="title1"></p>
And so on

HTML page is not displaying all records but overwriting previous results

I have two child records under Sensor, but its only displaying the last one, since it overwrites the previous record. How can I display the two results under each other or side by side?
This section in code is the one pulling records from Firebase realtime database.
get(child(dbref, "Sensor"))
.then((snapshot)=>{
snapshot.forEach((child)=>{
id_PumpID.innerHTML = "Pump ID: " + child.val().PumpID
id_StartTime.innerHTML = "StartTime: " + child.val().StartTime;
id_Cycle.innerHTML = "Cycle: " + child.val().Cycle;
id_Duration.innerHTML = "Duration: " + child.val().Duration;
id_GalsPumped.innerHTML ="GalsPumped: " + child.val().GalsPumped;
})
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="pump">
<br><br>
<h3 id="id_Cycle" type="number"></h3>
<h3 id="id_Duration" type="number"></h3>
<h3 id="id_GalsPumped" type="number"></h3>
<h3 id="id_PumpID" type="number"></h3>
<h3 id="id_StartTime" type="text"></h3>
<br><br>
</div>
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.9.4/firebase-app.js";
//config firebase
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxx-qE4zUGw",
authDomain: "pump-a559c.firebaseapp.com",
databaseURL: "https://pump-a559c-default-rtdb.firebaseio.com",
projectId: "pump-a559c",
storageBucket: "pump-a559c.appspot.com",
messagingSenderId: "838180391277",
appId: "1:838180391277:web:df22c7d634310ae135b264",
measurementId: "G-K66Z05LFCD"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
import {getDatabase, set, get, update, remove, ref, child}
from "https://www.gstatic.com/firebasejs/9.9.4/firebase-database.js";
const db = getDatabase();
const dbref = ref(db);
get(child(dbref, "Sensor"))
.then((snapshot)=>{
snapshot.forEach((child)=>{
id_PumpID.innerHTML = "Pump ID: " + child.val().PumpID
id_StartTime.innerHTML = "StartTime: " + child.val().StartTime;
id_Cycle.innerHTML = "Cycle: " + child.val().Cycle;
id_Duration.innerHTML = "Duration: " + child.val().Duration;
id_GalsPumped.innerHTML ="GalsPumped: " + child.val().GalsPumped;
})
});
window.onload();
</script>
</body>
</html>
I solved the issue with switch - case statements. Please see the full code below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="refresh" content="5">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drainage Pump Monitor</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
overflow:hidden;padding:13px 14px;word-break:normal;}
.tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
font-weight:normal;overflow:hidden;padding:13px 14px;word-break:normal;}
.tg .tg-l183{background-color:#96fffb;border-color:inherit;font-family:"Courier New", Courier, monospace !important;font-size:16px;
font-weight:bold;text-align:left;vertical-align:top}
.tg .tg-0pky{border-color:inherit;text-align:left;vertical-align:top}
</style>
<header>
<h1>DRAINAGE PLAN</h1>
<h2>7310 S Cypresshead dr, Parkland FL 33067</h2>
</header>
<main>
<h2>Pump Monitor</h2>
<table id="pump_table" style="margin-top:130px; margin-left:10px;" class="tg" align="right">
<thead>
<tr>
<th class="tg-l183">PUMP</th>
<th class="tg-l183">START-TIME</th>
<th class="tg-l183">DURATION(mins)</th>
<th class="tg-l183">PUMPED(gals)</th>
<th class="tg-l183">CYCLE</th>
<th class="tg-l183">STATUS</th>
</tr>
</thead>
</table>
</main>
<footer>
<p>Copyright © <script>document.write(new Date().getFullYear());</script>, Innovative-Appliances. LLC </p>
</footer>
<script type="module">
// Import firebase app
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.9.4/firebase-app.js";
// Configure Firebase
const firebaseConfig = {
apiKey: "Axxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxx.firebaseapp.com",
databaseURL: "https://xxxxxxxxxxxxxx-default-rtdb.firebaseio.com",
projectId: "pump-a559c",
storageBucket: "pump-a559c.appspot.com",
messagingSenderId: "838180391277",
appId: "1:838180391277:web:df22c7d634310ae135b264",
measurementId: "xxxxxxxxxxxxxxxxxx"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Import the Firebase database
import {getDatabase, set, get, update, remove, ref, child}
from "https://www.gstatic.com/firebasejs/9.9.4/firebase-database.js";
const db = getDatabase();
const dbref = ref(db);
const heartBeat = Math.round(Date.now() / 1000);
get(child(dbref, "Sensor"))
.then((snapshot) => {
snapshot.forEach((child) => {
var bg_color = '#00FF00';
console.log(child.val().Heartbeat);
console.log("html heartbeat" + heartBeat);
// Check the heartbeat and report power failure if not found
if(child.val().Heartbeat < (heartBeat - 15))
{
console.log("no heart beat detected");
let table = document.querySelector('table');
let template = `
<tr>
<td bgcolor='red'>${"pump" + child.val().PumpID}</td>
<td bgcolor='red'>CONTROLLER FAILURE</td>
</tr>`;
table.innerHTML += template;
} else {
switch (child.val().Status) {
case "OFF":
// Set the color of row to red if no water flow is detected.
bg_color = 'yellow';
let table = document.querySelector('table');
let template = `
<tr>
<td bgcolor="${bg_color}">${"pump"+child.val().PumpID}</td>
<td bgcolor="${bg_color}">${child.val().StartTime}</td>
<td bgcolor="${bg_color}">${child.val().Duration}</td>
<td bgcolor="${bg_color}">${child.val().GalsPumped}</td>
<td bgcolor="${bg_color}">${child.val().Cycle}</td>
<td bgcolor="${bg_color}">${child.val().Status}</td>
</tr>`;
table.innerHTML += template;
break;
case "ON":
// Set the color of row to green
// if water flow is detected.
bg_color = '#00FF00';
let table2 = document.querySelector('table');
let template2 = `
<tr>
<td bgcolor="${bg_color}">${"pump"+child.val().PumpID}</td>
<td bgcolor="${bg_color}">${child.val().StartTime}</td>
<td bgcolor="${bg_color}">${child.val().Duration}</td>
<td bgcolor="${bg_color}">${child.val().GalsPumped}</td>
<td bgcolor="${bg_color}">${child.val().Cycle}</td>
<td bgcolor="${bg_color}">${child.val().Status}</td>
</tr>`;
table2.innerHTML += template2;
break;
case "FAIL":
// Set the color of row to red
// if pump failure is detected.
bg_color = 'red';
let table3 = document.querySelector('table');
let template3 = `
<tr>
<td bgcolor='red'>${"pump" + child.val().PumpID}</td>
<td bgcolor='red'>PUMP FAILURE</td>
</tr>`;
table3.innerHTML += template3;
break;
} // End of switch
} // End of else
})
});
</script>
</body>
</html>

Delete button is not able to delete buttons. It is responsive in the console but nothing else

i'm having trouble using my delete button with my code. Instead of deleting an object, it creates a new one. code is under render items function. i've tried several things but it seems like my biggest problem is the placement of the rederItems function in the if statement. I also added the html to show you how that looks like too. Thanks!
// selectors
var nameOfItem = document.getElementById("nameOfItem");
var saveOfItem = document.getElementById("nameOfItem");
var shoppingList = document.getElementById("shoppingListContainer");
var nameArray = ["tea","bread","rice"]
// var nameArray = []
var setCart = [];
var getIngredientsForCart = localStorage.getItem
var emptyListText = document.getElementById("emptyList")
var removeButton = document.getElementById('removeItem');
var saveItems = document.getElementById("saveItems");
var cart = document.getElementById("shoppingListContainer")
cart.style.visibility = 'hidden';
saveItems.style.visibility = 'hidden'
saveItems.addEventListener('click', function() {
console.log('saved')
setCart.push(entry);
localStorage.setItem('cart', JSON.stringify(newArray));
});
/*
<li class="list-group-item" id="numberOfItems">1</li>
<li class="list-group-item" id="nameOfItem"></li>
<li class="list-group-item" id="removeItem"></li>
*/
// get from local storage
// var food = JSON.parse(localStorage.getItem("Ingredients"))
// console.log(food)
// nameArray = food
// --------------------------------
// render Item function
// --------------------------------
function renderItems() {
for (i = 0; i < nameArray.length; i++) {
var row = document.createElement("div");
row.setAttribute("class", "row");
var col2 = document.createElement("div");
var col3 = document.createElement("div");
col2.setAttribute("class", "col-8 item-name");
col3.setAttribute("class", "col-2 item-delete");
var newButton = document.createElement('button');
newButton.textContent = 'Delete';
newButton.setAttribute("data-item-idx", i);
newButton.addEventListener('click', function(event){
console.log(event.target.dataset.itemIdx)
var selectedItem = parseInt(event.target.dataset.itemIdx);
if(nameArray.splice(selectedItem, 1)){
console.log(nameArray)
renderItems()
}
})
col2.textContent = nameArray[i];
col3.appendChild(newButton);
row.appendChild(col2);
row.appendChild(col3);
shoppingList.appendChild(row);
}
}
// --------------------------------
// shopping Cart function
// --------------------------------
function shoppingCart() {
emptyListText.style.visibility = 'hidden';
cart.style.visibility = 'visible';
saveItems.style.visibility = 'visible'
renderItems()
}
// execute Function
shoppingCart()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous" />
<link href="https://fonts.googleapis.com/css?family=Open+Sans&display=swap" rel="stylesheet" />
<title>Meal Plan</title>
<link rel="stylesheet" href="../css/shoppinglist.css">
</head>
<body>
<div>
<h1>Shopping List</h1>
search recipes
</div>
<h1 id="emptyList">Cart is Empty :(</h1>
<section id="shoppingListContainer" class="container">
</section>
<button id="saveItems">Save Items</button>
</body>
<!-- <script src="/projects/mealPlan/assets/js/script.js"></script> -->
<script src="../js/shoppingList.js"></script>
</html>
You are calling renderItems() again on delete but you are never actually clearing the existing rendered html.
Simply adding shoppingList.innerHTML = ""; to the start of the renderItems() function will clear the html each time render runs.

Displaying content of xml data in html file is not working

I want to display the content of a XML file into a html file.
I have seen and tried the example shown in the following link
https://www.youtube.com/watch?v=VxKGVb0oOBw
I have created html file copying the exactly the code in that example. Here is the code of my first html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=""UTF-8>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Test 1oading xml</title>
</head>
<body>
<div id='content'>
<table id="books" cellpadding="10px" style="text-align:left;">
<thead>
<tr><th>Author</th><th>Title</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script>
let xmlContent = '';
let tableBooks = document.getElementById('books');
fetch('books.xml').then((response)=>{
response.text().then((xml)=>{
xmlContent = xml;
let parser = new DOMParser();
let xmlDOM = parser.parseFromString(xmlContent, 'appliction/xml');
let books = xmlDOM.querySelectorAll('book');
books.forEach(bookXmlNode => {
let row = document.createElement('tr');
//author
let td = document.createElement('td');
td.innerText = bookXmlNode.children[0].innerHTML;
row.appendChild(td);
//title
let td = document.createElement('td');
td.innerText = bookXmlNode.children[1].innerHTML;
row.appendChild(td);
tableBooks.children[1].appendChild(row);
});
});
});
</script>
</body>
</html>
copied the xml file content from here https://learn.microsoft.com/en-us/previous-versions/windows/desktop/ms762271(v%3Dvs.85) .. saved the file as books.xml in the same folder of the html file. Although Ideally I want to display data from external xml file so that the data can be updated dynamically.
When I open the html file it is not showing the xml data.
I have also tried with the code from this link.
https://www.encodedna.com/2014/07/extract-data-from-an-xml-file-using-javascript.htm
Thant is also not working.
How to display data of an (external) xml file into a html file
Screenshot of inspect page. The top one for the code of the you tube video.
The botom one is for the code from https://www.encodedna.com/2014/07/extract-data-from-an-xml-file-using-javascript.htm
Your code is basically correct but you have a few typos. Try the code below, which works for me. As other commenters have mentioned, you can't just open the file, you need a web server to serve it up. The video you link to does this using Live Server in Visual Studio Code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="" UTF-8>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Test 1oading xml</title>
</head>
<body>
<div id='content'>
<table id="books" cellpadding="10px" style="text-align:left;">
<thead>
<tr>
<th>Author</th>
<th>Title</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script>
let xmlContent = '';
let tableBooks = document.getElementById('books');
fetch('books.xml').then((response) => {
response.text().then((xml) => {
xmlContent = xml;
let parser = new DOMParser();
let xmlDOM = parser.parseFromString(xmlContent, 'application/xml');
let books = xmlDOM.querySelectorAll('book');
books.forEach(bookXmlNode => {
let row = document.createElement('tr');
//author
let td = document.createElement('td');
td.innerText = bookXmlNode.children[0].innerHTML;
row.appendChild(td);
//title
let td2 = document.createElement('td');
td2.innerText = bookXmlNode.children[1].innerHTML;
row.appendChild(td2);
tableBooks.children[1].appendChild(row);
});
});
});
</script>
</body>
</html>
The typos are: id="books", 'application/xml' and you can't use td as a variable name twice.
By the way, when you have problems like this the first place to look is in the browser's console window. Hit F12 after the browser has launched and failed to show your data, and go to Console if it's not selected: it will show you any errors and where they are coming from. If you're using VS Code you can actually debug the script as well I think, meaning you can single-step through it seeing what's going on.

Categories