How to multiply XML values in an XML table? - javascript

XML table (as rendered in Firefox 47.0.1)
The .XML file doesn't contain nodes for Total Price, but I can still derive it in the XML table by multiplying PRICE * QUANTITY.
I am aware of this solution:
y[i].getElementsByTagName("PRICE")[0].childNodes[0].nodeValue * y[i].getElementsByTagName("QUANTITY")[0].childNodes[0].nodeValue
However I would like to multiply variables instead:
p * q
So I have already declared variables for PRICE and QUANTITY (p and q):
var p = y[i].getElementsByTagName("PRICE")[0].childNodes[0].nodeValue
var q = y[i].getElementsByTagName("QUANTITY")[0].childNodes[0].nodeValue
But this only yields the correct result for the first row (Unit 1).
Why is this not working?
Here's my example.xml
<?xml version="1.0" encoding="UTF-8"?>
<CUSTOMER_ORDER>
<UNIT>
<NAME>Unit 1</NAME>
<QUANTITY>45</QUANTITY>
<PRICE>25.99</PRICE>
</UNIT>
<UNIT>
<NAME>Unit 2</NAME>
<QUANTITY>209</QUANTITY>
<PRICE>9.95</PRICE>
</UNIT>
<UNIT>
<NAME>Unit 3</NAME>
<QUANTITY>80</QUANTITY>
<PRICE>14.99</PRICE>
</UNIT>
<UNIT>
<NAME>Unit 4</NAME>
<QUANTITY>156</QUANTITY>
<PRICE>35.88</PRICE>
</UNIT>
<UNIT>
<NAME>Unit 5</NAME>
<QUANTITY>25</QUANTITY>
<PRICE>199.00</PRICE>
</UNIT>
</CUSTOMER_ORDER>
Here's my test html
<!DOCTYPE html>
<html>
<style>
table,
th,
td {
border: 2px solid black;
border-collapse: collapse;
}
th,
td {
padding: 5px;
}
</style>
<body>
<body onload="loadXMLDoc()">
<table id="test"></table>
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
testFunction(xmlhttp);
}
};
xmlhttp.open("GET", "example.xml", true);
xmlhttp.send();
}
function testFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Unit</th><th>Price</th><th>Quantity</th><th>Total Price</th></tr>";
var y = xmlDoc.getElementsByTagName("UNIT");
for (i = 0; i > y.length; i++);
var p = y[i].getElementsByTagName("PRICE")[0].childNodes[0].nodeValue;
var q = y[i].getElementsByTagName("QUANTITY")[0].childNodes[0].nodeValue;
for (i = 0; i < y.length; i++)
{
table += "<tr><td>" +
y[i].getElementsByTagName("NAME")[0].childNodes[0].nodeValue +
"</td><td>" +
y[i].getElementsByTagName("PRICE")[0].childNodes[0].nodeValue +
"</td><td>" +
y[i].getElementsByTagName("QUANTITY")[0].childNodes[0].nodeValue +
"</td><td>" +
p * q + // This is the total price column yielding 1169.55 across all rows.
"</td></tr>";
}
document.getElementById("test").innerHTML = table;
}
</script>
</body>
</html>

The problem turned out to be syntax and the solution is very simple. Thanks to everyone who contributed their input.
You can see the final testfunction(xml) here:
function testFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Unit</th><th>Price</th><th>Quantity</th><th>Total Price</th></tr>";
var y = xmlDoc.getElementsByTagName("UNIT");
for (i = 0; i < y.length; i++)
{
var p = y[i].getElementsByTagName("PRICE")[0].childNodes[0].nodeValue;
var q = y[i].getElementsByTagName("QUANTITY")[0].childNodes[0].nodeValue;
var n = y[i].getElementsByTagName("NAME")[0].childNodes[0].nodeValue;
table += "<tr><td>" +
n +
"</td><td>" +
p +
"</td><td>" +
q +
"</td><td>" +
p*q + // This is the total price column.
"</td></tr>";
}
document.getElementById("test").innerHTML = table;
}

Related

Populating an HTML table from an external XML

I have come across a problem while fetching data from an external XML document with JS. I have been following the w3schools tutorial for AJAX XML so far, but I ran into something I couldn't solve. I have a XML that looks like this:
<root>
<document-id>
<author>Tom Riddle</autor>
<title>abzy</title>
<year>1995</year>
</document-id>
<document-id>
<author>Tom Riddle</autor>
<title>abzy</title>
</document-id>
<document-id>
<author>Tom Riddle</autor>
<year>1995</year>
</document-id>
</root>
I want to dynamically access the data inside the XML and create a table while doing so. It works fine for the one DOM Element all documents share, but it gives me an error as soon as I include year or title. I guess it's because the tags are empty in some parts of the tree. Is there a way to ignore empty tags and only write something in the column if there is a value inside? Thank you for your time and knowledge.
THIS IS THE ASSOCIATED HTML
<body>
<header>
<h1>Reading Data from XML Files</h1>
</header>
<main>
<button type="button" onclick="loadDoc()">Get my CD collection</button>
<table id="demo">
</table>
</main>
<script>
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
myFunction(this);
}
xhttp.open("GET", "books.xml");
xhttp.send();
}
function myFunction(xml) {
const xmlDoc = xml.responseXML;
const x = xmlDoc.getElementsByTagName("document-id");
console.log(x)
let table="<tr><th>Author</th><th>Title</th><th>Year</th></tr>";
for (let i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue +
"</tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
Check for existence before you try to access the children.
function getText(node, tag) {
var elem = node.getElementsByTagName(tag);
return elem ? elem.[0].childNodes[0].nodeValue : '';
}
for (let i = 0; i <x.length; i++) {
var cells = ['author', 'title', 'year'].map(function (tag) {
return "<td>" + getText(x[i], tag) + "</td>";
}).join("");
table += "<tr>" + cells + "</tr>");
}
try this with in line solution to check if tag exist in xml
function myFunction(xml) {
const xmlDoc = xml.responseXML;
const x = xmlDoc.getElementsByTagName("document-id");
console.log(x)
let table="<tr><th>Author</th><th>Title</th><th>Year</th></tr>";
for (let i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue +
"</td><td>" + ((x[i].getElementsByTagName("title")[0] == undefined)?"": x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue ) +
"</td><td>" +
((x[i].getElementsByTagName("year")[0] == undefined)?"": x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue ) +
"</tr>";
}
document.getElementById("demo").innerHTML = table;
}

How to write an AJAX call to get an XML file?

I need to write a web page with a button “Get Flight Information”. When the user clicks this button, write an AJAX call to get the XML file that you wrote in Question 1, parse the XML into a Javascript object, and then display the Javascript object on the web page exactly as
follows:
Here is my code so far. I am extremely new to this so please go easy guys! :
XML:
<?xml version="1.0" encoding="UTF-8"?>
<flightInfo>
<Date>02OCT19</Date>
<Flight> VA 1429 </Flight>
<Depart>Sydney</Depart>
<Arrive>Cairns</Arrive>
<Boarding>Gate 35 At 1855</Boarding>
<Carrier>Virgin Australia</Carrier>
</flightInfo>
<?xml version="1.0" encoding="UTF-8"?>
HTML:
<html>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>
<button type="button" onclick="loadDoc()">Get flight
information</button>
<br><br>
<table id="demo"></table>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "Question1.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Depart</th><th>Arrive</th></tr>";
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("Depart")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("Arrive")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
</html>
<html>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>
<button type="button" onclick="loadDoc()">Get flight
information</button>
<br><br>
<table id="demo"></table>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "Question1.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table=`<tr><th>Depart</th><th>Arrive</th></tr>`;
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.length; i++) {
table += `<tr><td>` +
x[i].getElementsByTagName("Depart")[0].childNodes[0].nodeValue +
`</td><td>` +
x[i].getElementsByTagName("Arrive")[0].childNodes[0].nodeValue +
`</td><td>` +
x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue +
`</td></tr>`;
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
</html>
I think this should help.
$(function(){
var data = '<?xml version="1.0" encoding="UTF-8"?><flightInfo><Date>02OCT19</Date><Flight> VA 1429 </Flight><Depart>Sydney</Depart><Arrive>Cairns</Arrive><Boarding>Gate 35 At 1855</Boarding><Carrier>Virgin Australia</Carrier></flightInfo>'
//Parse the givn XML
var xmlDoc1 = $.parseXML( data );
var $xml1 = $(xmlDoc1);
// Find Person Tag
var $flightInfo = $xml1.find("flightInfo");
$flightInfo.each(function(){
var Date = $(this).find('Date').text(),
Depart = $(this).find('Depart').text(),
Arrive = $(this).find('Arrive').text() ;
$("#data" ).append('<li>' + Date + ' - ' + Depart+ ' - ' + Arrive + '</li>');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="data"></ul>
first of all you need to parse your data in xml object as below after that you can read it.
try below solution.
<ul id="data"></ul>
<script>
$(function(){
var data = '<?xml version="1.0" encoding="UTF-8"?><flightInfo><Date>02OCT19</Date><Flight> VA 1429 </Flight><Depart>Sydney</Depart><Arrive>Cairns</Arrive><Boarding>Gate 35 At 1855</Boarding><Carrier>Virgin Australia</Carrier></flightInfo>'
//Parse the givn XML
var xmlDoc1 = $.parseXML( data );
var $xml1 = $(xmlDoc1);
// Find Person Tag
var $flightInfo = $xml1.find("flightInfo");
$flightInfo.each(function(){
var Date = $(this).find('Date').text(),
Depart = $(this).find('Depart').text(),
Arrive = $(this).find('Arrive').text() ;
$("#data" ).append('<li>' + Date + ' - ' + Depart+ ' - ' + Arrive + '</li>');
});
});
</script>
check live demo:
http://jsfiddle.net/ru92p4en/

How To Convert CSV file to HTML table

i have csv file with the content :
heading1,heading2,heading3,heading4,heading5
value1_1,value2_1,value3_1,value4_1,value5_1
value1_2,value2_2,value3_2,value4_2,value5_2
I create Javascript/HTML code to pick up that file and display the content
<html>
<head>
<title>show csv</title>
</head>
<body>
<input type="file" id="fileinput" multiple />
<div id="result"></div>
<script type="text/javascript">
function readMultipleFiles(evt) {
//Retrieve all the files from the FileList object
var files = evt.target.files;
if (files) {
for (var i=0, f; f=files[i]; i++) {
var r = new FileReader();
r.onload = (function(f) {
return function(e) {
var contents = e.target.result;
var res = document.getElementById("result");
res.innerHTML = "Got the file<br>"
+"name: " + f.name + "<br>"
+"type: " + f.type + "<br>"
+"size: " + f.size + " bytes</br>"
+ "starts with: " + contents;
};
})(f);
r.readAsText(f);
}
} else {
alert("Failed to load files");
}
}
document.getElementById('fileinput').addEventListener('change',readMultipleFiles, false);
</script>
</body>
</html>
and the output is like :
output
question : How can i convert the content or the data to array and showing as html table ?
thanks for any help.
You can convert csv data into array and then into html table. I have added \n into your new line. Please add the \n to your code when there is a new line.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
table {
border-collapse: collapse;
border: 2px black solid;
font: 12px sans-serif;
}
td {
border: 1px black solid;
padding: 5px;
}
</style>
</head>
<body>
<div id='container'></div>
<script type="text/javascript"charset="utf-8">
var data = 'heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2';
var lines = data.split("\n"),
output = [],
i;
for (i = 0; i < lines.length; i++)
output.push("<tr><td>"
+ lines[i].slice(0,-1).split(",").join("</td><td>")
+ "</td></tr>");
output = "<table>" + output.join("") + "</table>";
var div = document.getElementById('container');
div.innerHTML = output;
</script>
</body>
</html>
I found Kapila Perera's answer to be very useful. However, the last element of each row was being cropped due to the slice(0,-1) use. Building on Perera's answer, in the example below I've used slice() instead.
I've also separated out the first row lines[0] as a header row and loop from 1 instead (which won't always be the case that csv contains headers but is explicitly called out in the example).
Finally, I've added the tbody tags when the output gets wrapped but this probably isn't required.
<script type="text/javascript"charset="utf-8">
var div = document.getElementById('container');
var data = 'heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2';
var lines = data.split("\n"), output = [], i;
/* HEADERS */
output.push("<tr><th>"
+ lines[0].slice().split(",").join("</th><th>")
+ "</th></tr>");
for (i = 1; i < lines.length; i++)
output.push("<tr><td>"
+ lines[i].slice().split(",").join("</td><td>")
+ "</td></tr>");
output = "<table><tbody>"
+ output.join("") + "</tbody></table>";
div.innerHTML = output;
</script>

Fetching XML Data with JavaScript

I feel like I'm going to pull my hair out. I am trying to take some data from an xml file and put it into a table using javascript. I have looked at and followed about a million examples, but for some reason, I can't get it to work. I've been using DreamWeaver, Notepad++ and Brackets.
This is my html file.
<head>
//<meta http-equiv="Content-Type" content="text/html; charset-UTF-8"/>
<script language="javascript" type="text/javascript" src="script2.js"></script>
<title>Computer Science Faculty Information</title>
<h1>Computer Science Faculty Information</h1>
<button onclick="readXML()">Read XML File</button>
<table id="first" border="1">
<tr>
<th>Name</th>
</tr>
</table>
my xml file
<?xml version="1.0?>
<department>
<employee>
<name>Ajay Katangur, Ph.D.</name>
<title>Program Coordinator</title>`
<office>CI 340</office>
<phone>361-825-2478</phone>
<email>ajay.katangur#tamucc.edu</email>
</employee>
</department>
and my js file
function readXML() {
"use strict";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
myFunction(xmlhttp);
}
};
xmlhttp.open("GET", "xml.xml", true);
xmlhttp.send();
}
function myFunction(xml) {
"use strict";
var x, i, xmlDoc, table;
xmlDoc = xml.responseXML;
table = "<tr><th>Name</th><th>Title</th><th>Office</th><th>Phone</th><th>Email</th><tr>";
x = xmlDoc.getElementsByTagName("employee");
for(i = 0; i < x.length; i++) {
table += "<tr><td>" + x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("office")[0].childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("phone")[0].childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("email")[0].childNodes[0].nodeValue + "</td></tr>";
}
document.getElementById("first").innerHTML = table;
}
I should mention that a large part of the js code here is from W3Schools. Please someone show me what I'm doing wrong. Thanks in advance.
Your code works as you can see in the snippet I've created below. However, as you noted in a comment, the problem is that your request isn't returning the XML file. Check the URL to make sure that it is correct.
Also make sure that your XML is correct. For example, your XML declaration is missing a quote mark, i.e., should be <?xml version="1.0"?> And make sure there are no spaces in the file before that declaration.
Run the snippet to see it work. You can edit the XML in the text box and click the button to see the changes.
function readXML() {
"use strict";
// simulated request
var xmlhttp={};
xmlhttp.responseText = window.data.value;
xmlhttp.responseXML = (new DOMParser()).parseFromString(xmlhttp.responseText, 'text/xml')
myFunction(xmlhttp);
/*
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
myFunction(xmlhttp);
}
};
xmlhttp.open("GET", "xml.xml", true);
xmlhttp.send();
}
*/
}
function myFunction(xml) {
"use strict";
var x, i, xmlDoc, table;
xmlDoc = xml.responseXML;
table = "<tr><th>Name</th><th>Title</th><th>Office</th><th>Phone</th><th>Email</th><tr>";
x = xmlDoc.getElementsByTagName("employee");
for (i = 0; i < x.length; i++) {
table += "<tr><td>" + x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("office")[0].childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("phone")[0].childNodes[0].nodeValue + "</td><td>" + x[i].getElementsByTagName("email")[0].childNodes[0].nodeValue + "</td></tr>";
}
document.getElementById("first").innerHTML = table;
}
textarea {
width: 90%;
height: 40em;
padding: 0.5em;
border: 1px solid black;
background-color: aliceblue;
}
table {
border-collapse: collapse;
}
td {
border: 1px lightgray solid;
padding: 2px;
}
<button onclick="readXML()">Read XML File</button>
<table id="first" border="1">
<tr>
<th>Name</th>
</tr>
</table>
<h4>XML:</h4>
<textarea id="data">
<?xml version="1.0" encoding="UTF-8" ?>
<department>
<employee>
<name>John Smith, Ph.D.</name>
<title>Program Coordinator</title>`
<office>CI 340</office>
<phone>000-000-0000</phone>
<email>John.Smith#tamucc.edu</email>
</employee>
</department>
</textarea>

How to read JSON data from a web server running PHP and MySQL?

I read example in http://www.w3schools.com/json/json_example.asp.
And I try it with my MySQL database and my PHP code. But it does not work.
I am a beginner and I don't know what it wrong.
Here is my PHP link: http://xebus2014.tk/demo.php
And I change w3school code like this:
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
border-bottom: 3px solid #cc9900;
color: #996600;
font-size: 30px;
}
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body>
<h1>Customers</h1>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://xebus2014.tk/demo.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].STT +
"</td><td>" +
arr[i].ID +
"</td><td>" +
arr[i].Name +
"</td><td>" +
arr[i].Singer +
"</td></tr>";
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
Did you set the response as Json String?
header("Content-Type: application/json; charset=UTF-8");
Your result is already an object, so you don't need to parse it using JSON.parse, just use it as is and pass it through the loop as is.
I don't know about the cross domain issue, but to run it, I go directly to your function... see this fiddle for a working loop using your output -- http://jsfiddle.net/fu3g5Loe/
OR you may use this in your PHP backend
echo json_encode('Your result set goes here'); // this will apply the correct JSON representation of your result set before echoing
Working Code
<body>
<h1>Customers</h1>
<div id="id01"></div>
<script>
/*
var xmlhttp = new XMLHttpRequest();
var url = "http://xebus2014.tk/demo.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
*/
var params = [{"STT":"1","ID":"123","Name":"Sexy Love","Singer":"T-ara"},{"STT":"2","ID":"456","Name":"Day By Day","Singer":"T-ara"},{"STT":"3","ID":"789","Name":"Cry Cry","Singer":"T-ara"}];
myFunction(params);
function myFunction(response) {
var arr = response;
var i;
var out = "<table>";
for(i = 0; i < response.length; i++) {
out += "<tr><td>" +
arr[i].STT +
"</td><td>" +
arr[i].ID +
"</td><td>" +
arr[i].Name +
"</td><td>" +
arr[i].Singer +
"</td></tr>";
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
</script>
</body>

Categories