I am trying to get an image to display in the table below, the image isn't displaying instead just the URL to the image is. Below is the what I have put into the HTML file. I have copied it off another site and also do not want the push button option and I am not sure how to get rid of that.
<div id="container">
<table id="demo"></table>
<button type="button" onclick="loadXMLDoc()">Get my CD collection</button>
<br><br>
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp);
}
};
xmlhttp.open("GET", "amateur.xml", true);
xmlhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var img = document.createElement("img");
var table="<tr><th>Rating</th><th>Title</th><th>Thumbnail</tr>";
var x = xmlDoc.getElementsByTagName("video");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("rating")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue +
"</td><td>" +
img.src = x[i].getElementsByTagName("thumbnail")[0].childNodes[0].nodeValue
document.write(img.src);
document.body.appendChild(img)"</td></tr>";;
}
document.getElementById("demo").innerHTML = table;
}
</script>
</div>
This is a sample of what the XML file looks like, it has been edited slightly as it is inappropriate for the content to be shown. The XML file is called "amateur.xml"
<?xml version="1.0" encoding="utf-8"?>
<videos>
<video id="1fb853907b9ca6add9ac">
<url>a.com</url>
<categories>A</categories>
<rating>100</rating>
<title>A</title>
<tags>A;a;AB</tags>
<duration>15</duration>
<thumbnail>http://i1.cdn2a.image.phncdn.com/m=eGcE8daaaa/videos/201011/03/148553/original/12.jpg</thumbnail>
</video>
<video id="d95ebc6a75c00d9926e7">
<url>http://ab.com</url>
<categories>A;B;An</categories>
<rating>100</rating>
<title>Sie spritzt ab</title>
<tags>a;b;as;d</tags>
<duration>65</duration>
<thumbnail>http://i0.cdn2a.image..phncdn.com/m=eGcE8daaaa/videos/201102/17/160998/original/12.jpg</thumbnail>
</video>
</videos>
Why is there a document.write(img.src)? Normally, you use that when you put it in into an <img> tag but then you don't need to create the image object, like:
for (i = 0; i <x.length; i++) {
var img = x[i].getElementsByTagName("thumbnail")[0].childNodes[0].nodeValue;
table += "<tr><td>" +
x[i].getElementsByTagName("rating")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue +
"</td><td><img src='"+img+"'></td></tr>";
}
Related
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;
}
I am trying to read data from a xml file and display them in my html file, but when I am trying to display my values I get "undefined" values for all the values.
I am a really new with ajax and xml so excuse my code if its horrible! I will appreciate if someone got a really briefly answer.
Here's my xml file:
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
<gesmes:subject>Reference rates</gesmes:subject>
<gesmes:Sender>
<gesmes:name>European Central Bank</gesmes:name>
</gesmes:Sender>
<Cube>
<Cube time="2019-01-25">
<Cube currency="USD" rate="1.1346"/>
<Cube currency="JPY" rate="124.72"/>
<Cube currency="BGN" rate="1.9558"/>
<Cube currency="CZK" rate="25.697"/>
<Cube currency="DKK" rate="7.4664"/>
<Cube currency="GBP" rate="0.86580"/>
....
My javascript code:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
returndata(this);
}
};
xhttp.open("GET", "rates.xml", true);
xhttp.send();
}
function returndata(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>currency</th><th>rates</th></tr>";
var x = xmlDoc.getElementsByTagName("Cube");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("currency")[0] +
"</td><td>" +
x[i].getElementsByTagName("rate")[0] +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
When I click the button I got the following result:
currency rates
undefined undefined
undefined undefined
undefined undefined
undefined undefined
.....
UPDATE Javascript code(fixed):
function returndata(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>currency</th><th>rates</th></tr>";
var x = xmlDoc.getElementsByTagName("Cube");
for (i = 2; i <x.length; i++) {
table += "<tr><td>" +
x[i].getAttribute("currency") +
"</td><td>" +
x[i].getAttribute("rate") +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
Okay now it works, thank you very much, i started my variable from the value 2 because when i am trying to have a while loop like (x!=null) my webpage it still loading forever and then breaks down..
i tried that one:
function returndata(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>currency</th><th>rates</th></tr>";
var x = xmlDoc.getElementsByTagName("Cube");
for (i = 0; i <x.length; i++) {
while (x!=null) {
table += "<tr><td>" +
x[i].getAttribute("currency") +
"</td><td>" +
x[i].getAttribute("rate") +
"</td></tr>";
}
}
document.getElementById("demo").innerHTML = table;
}
I have this HTML file where if the user clicks on "View questions", it should display the parsed data that I receive. Right now I am working with a JSON test file. It displays the data fine, but I need to dynamically add checkboxes using Javascript for when the data is displayed. And when the user clicks on a checkbox, that data can be sent through Ajax to the backend. How can I achieve this? Any help would be appreciated. Thanks.
<button type=button class="lg=button" id="btn">View questions</button>
<p id="response"></p>
<script>
var resp = document.getElementById("response");
var btn = document.getElementById("btn");
btn.addEventListener("click", function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://learnwebcode.github.io/json-example/animals-1.json", true);
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) {
console.log(xhr.responseText);
var ourData = JSON.parse(xhr.responseText);
//console.log(ourData);
renderHTML(ourData);
}
}
xhr.send();
});
function renderHTML(data) {
var htmlString = "";
for (i = 0; i < data.length; i++) {
htmlString += "<p>" + data[i].name + " is a " + data[i].species + " that likes to eat ";
}
htmlString += '.</p>';
resp.insertAdjacentHTML('beforeend', htmlString);
}
</script>
It displays the data fine, but I need to dynamically add checkboxes using Javascript for when the data is displayed you need to put input type checkbox while rendering it
<input id="checkBox" type="checkbox">
You can add event listener to do any logic based on click event on those checkbox.
var resp = document.getElementById("response");
var btn = document.getElementById("btn");
btn.addEventListener("click", function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://learnwebcode.github.io/json-example/animals-1.json", true);
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) {
console.log(xhr.responseText);
var ourData = JSON.parse(xhr.responseText);
//console.log(ourData);
renderHTML(ourData);
}
}
xhr.send();
});
function renderHTML(data) {
var htmlString = "";
for (i = 0; i < data.length; i++) {
htmlString += "<p><input type='checkbox'>" + data[i].name + " is a " + data[i].species + " that likes to eat ";
}
htmlString += '.</p>';
resp.insertAdjacentHTML('beforeend', htmlString);
}
<button type=button class="lg=button" id="btn">View questions</button>
<p id="response"></p>
I have this code from w3school works like a charm:
<!DOCTYPE html>
<html>
<body>
<h1>Customers</h1>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.w3schools.com/website/customers_mysql.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].Name +
"</td><td>" +
arr[i].City +
"</td><td>" +
arr[i].Country +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
but when I repeat the script like this it doesn't work:
<!DOCTYPE html>
<html>
<body>
<h1>Customers</h1>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.w3schools.com/website/customers_mysql.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].Name +
"</td><td>" +
arr[i].City +
"</td><td>" +
arr[i].Country +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
</script>
<h1>Buyers</h1>
<div id="id02"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.w3schools.com/website/customers_mysql.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].Name +
"</td><td>" +
arr[i].City +
"</td><td>" +
arr[i].Country +
"</td></tr>";
}
out += "</table>";
document.getElementById("id02").innerHTML = out;
}
</script>
</body>
</html>
What variable name should I change? I did the script once it worked but twice it didn't work.
I tried changing variable but it didn't work
I changed all the variable names.
Your two scripts exist in the same JS environment. They both create global variables with the same name and interfere with each other.
Wrap each script in an IIFE to create a new scope for each one to operate in.
<script>
(function () {
// Your code here
})();
</script>
It doesn't work because you're executing AJAX call across domains. You can't do an ajax call like that unless you are calling a page on the same domain. There are workarounds, but this is the problem in your case.
Instead create a local file to test your AJAX with.
This is why it works on the w3 Schools site, but not on your own code.
<html>
<head>
</head>
<body>
<div id="content"></div>
<script>
function handleResponse(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
// in production code, item.text should have the HTML entities escaped.
document.getElementById("content").innerHTML += "<br>" +item.volumeInfo.title+"<br>"+item.volumeInfo.imageLinks.thumbnail;
}
}
</script>
<script src="https://www.googleapis.com/books/v1/volumes/buc0AAAAMAAJ"></script>
</body>
</html>
Here I am Trying to Get Details of The Book Through Specific ID from the Google Books Please Help in JavaScript and JSON
You can get the information about a particular book by making xhr request. I have created a function which return title and thumbanil of particular Book ID:
function getBookDetails(id) {
var xmlhttp = new XMLHttpRequest();
var url = "https://www.googleapis.com/books/v1/volumes/" + id;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var item = JSON.parse(xmlhttp.responseText);
document.getElementById("content").innerHTML += "<br>" + item.volumeInfo.title + "<br>" + "<img src=\""+item.volumeInfo.imageLinks.thumbnail+"\" >";
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
getBookDetails("buc0AAAAMAAJ");
Working Fiddle