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>
Related
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/
I am attempting to display the data from a XML file to my website via JavaScript. I have used this JavaScript code on its own just with a basic HTML document and it works fine, displaying the data and allowing me to click and view other data in from the XML file.
However, when I copied the code to a page of my website, the code won't run and I keep getting the error message "Cannot read property 'getElementsByTagName' of null". I find this bizarre as it is the exact same code that I used with a basic HTML page and it worked fine...
I have attached the HTML from my website below. Any advice or a fixstrong text would be greatly appreciated.
<section id="middle_XML">
<h1>BOOK LIST</h1>
<div align ='center'>
<p>Click on a CD to display album information.</p>
<p id='showBook'></p>
<table id="demo"></table>
</div>
<script>
var x,xmlhttp,xmlDoc
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "booklist.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
x = xmlDoc.getElementsByTagName("book");
table="<tr><th>Artist</th><th>Title</th></tr>";
for (i = 0; i <x.length; i++) {
table += "<tr onclick='displayBook(" + i + ")'><td>";
table += x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
table += "</td><td>";
table += x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue;
table += "</td></tr>";
}
document.getElementById("demo").innerHTML = table;
function displayBook(i) {
document.getElementById("showBook").innerHTML =
"Artist: " +
x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue +
"<br>Title: " +
x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue +
"<br>Year: " +
x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue +
"<br>About: " +
x[i].getElementsByTagName("about")[0].childNodes[0].nodeValue +
"<br>Price: " +
x[i].getElementsByTagName("price")[0].childNodes[0].nodeValue;
}
</script>
</section>
Below is the code that works on a basic HTML page. Why won't it work when copied across on to my webpage?
<!DOCTYPE html>
<html>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>
<div align ='center'>
<p>Click on a CD to display album information.</p>
<p id='showBook'></p>
<table id="demo"></table>
</div>
<script>
var x,xmlhttp,xmlDoc
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "booklist.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
x = xmlDoc.getElementsByTagName("book");
table="<tr><th>Artist</th><th>Title</th></tr>";
for (i = 0; i <x.length; i++) {
table += "<tr onclick='displayBook(" + i + ")'><td>";
table += x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
table += "</td><td>";
table += x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue;
table += "</td></tr>";
}
document.getElementById("demo").innerHTML = table;
function displayBook(i) {
document.getElementById("showBook").innerHTML =
"Artist: " +
x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue +
"<br>Title: " +
x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue +
"<br>Year: " +
x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue +
"<br>About: " +
x[i].getElementsByTagName("about")[0].childNodes[0].nodeValue +
"<br>Price: " +
x[i].getElementsByTagName("price")[0].childNodes[0].nodeValue;
}
</script>
</body>
</html>
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;
}
Given this code,
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>
<form>
<input type="text" id="word" value=""/>
<button type="button" onclick="loadDoc()">Retrieve data</button>
<br>
</form>
<br><br>
<table id="demo"></table>
<script type="text/javascript">// <![CDATA[
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
};
xhttp.open("GET", "URL" + $('#word').val(), true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Japanese</th><th>Pronunciation</th><th>English</th></tr>";
var x = xmlDoc.getElementsByTagName("json");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("japanese")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("pronunciation")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("english")[0].childNodes[0].nodeValue +
"</td>" + " " + "</tr>";
}
document.getElementById("demo").innerHTML = table;
}
// ]]></script>
How could I skip the "pronunciation" tag whenever it has no value?
To be a little more specific, my XML file has different tags - "japanese" (a word or kanji), "pronunciation" (how the word is read, in hiragana, and only has a value when it's a kanji) and "english" (meaning of the word).
The current code does not work whenever a value is missing for the "pronunciation" tag, which means that every single word without a pronunciation will cause the site not to display anything.
XML File:
<json> //This entry has pronunciation
<japanese>原爆</japanese>
<pos>n</pos>
<pronunciation>げんばく</pronunciation>
<english>(abbr) (See 原子爆弾) atomic bomb A-bomb</english>
</json>
<json> //This entry does not have pronunciation as it is not needed
<japanese>ダム</japanese>
<pos>n</pos>
<english>dam/(adj-f)</english>
<english>dumb</english>
</json>
Thanks!
From your sample data, the pronunciation element is completely omitted when not needed. So getElementsByTagName("pronunciation") returns undefined, and because of that, you can't get [0] from it.
You can test what comes back and respond appropriately, like this:
var pron = getElementsByTagName("pronunciation");
if (pron) { table += pron[0].childNodes[0].nodeValue; }
This assumes you split the one long assignment to 'table', into separate parts. In general, you may find it useful to factor this out into a function like:
function getOptionalContentAsTD(ename) {
var el = getElementsByTagName(ename);
var txt = "";
if (el) { txt = el[0].childNodes[0].nodeValue; }
return("<td>" + txt + "</td>");
}
I didn't test this, so there's probably a typo, but it's gives the idea.
Hope that helps.
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>