How to fetch child node values from xml file using javascript - javascript

I can fetch the <name> tag value from the XML below, but I can't fetch all of the <image><url> values:
<?xml version='1.0' encoding='ISO-8859-1'?>
<gallery>
<name>abc</name>
<email><![CDATA[smith#email.com]]></email>
<images>
<image>
<url><![CDATA[g2pic3.jpg]]></url>
<caption><![CDATA[Red Sun]]></caption>
</image>
<image>
<url><![CDATA[g2pic4.jpg]]></url>
<caption><![CDATA[Eiffel Tower]]></caption>
</image>
</images>
</gallery>
Here is my javascript code. I want to fetch all of the values included in
the <images> tag, but am having trouble with this part.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
}
xhttp.open("GET", "template.xml", true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
nameList = xmlDoc.getElementsByTagName("name");
var nameList = nameList[0].childNodes;
document.getElementById("demo").innerHTML = xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
}
//xmlDoc.getElementsByTagName("gallery").item(0).firstChild.nodeValue;
</script>
</body>
</html>

Pretty sure there are much better solutions to this. My plain old js is a little rusty.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
}
xhttp.open("GET", "template.xml", true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
// Create a object gallery to store the values.
var gallery = {};
gallery.name = xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
gallery.email = xmlDoc.getElementsByTagName("email")[0].childNodes[0].nodeValue;
// Put all image elements into xmlImages
var xmlImages = xmlDoc.getElementsByTagName("image");
// Add an empty array to gallery
gallery.image = [];
// Iterate over all images in xmlImages
for(var i = 0; i < xmlImages.length; i++) {
var xmlImage = xmlImages[i];
// Create an new object and add url and caption values to it
var image = {};
image.url = xmlImage.getElementsByTagName("url")[0].childNodes[0].nodeValue;
image.caption = xmlImage.getElementsByTagName("caption")[0].childNodes[0].nodeValue;
// Add the image object to the gallery.image array
gallery.image.push(image);
}
// Quick and dirty, create a string with html tag to present the result
var html = "name: " + gallery.name + "<br>" +
"email: " + gallery.email + "<br>" +
"images:<br><ul>";
for(var i = 0; i < gallery.image.length; i++) {
html += "<li>image" + i + ":<br>";
html += "<ul><li>url: " + gallery.image[i].url + "</li>";
html += "<li>caption: " + gallery.image[i].caption + "</li></ul>";
}
html += "</ul>";
document.getElementById("demo").innerHTML = html;
}
</script>
</body>
</html>

Related

How to get multiple XMLHttpRequests to occur serially?

I have the following code, which works (sort of). When I run it, the page displays information about the two coins, but returns 'undefined' for the coin price. The call to alert() indicates that the getCoinPrice function is running AFTER the main code. How do you execute the code so that the function call happens serially? If that's not possible, would it be better to learn to use the Fetch API?
Here's the code, in its entirety:
<html>
<body>
<h2>Use the XMLHttpRequest to get the content of a file.</h2>
<p id="demo"></p>
<script>
function getCoinPrice(id) {
var xhr = new XMLHttpRequest();
var URL = "https://api.coinmarketcap.com/v2/ticker/" + id + "/";
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var Obj = JSON.parse(xhr.responseText);
var price = Obj.data.quotes.USD.price;
alert(price);
return(price);
}
}
xhr.open("GET", URL, true);
xhr.send();
}
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
var coins = [ "BTC","ETH" ]
for(j=0; j < coins.length; j++) {
for(i=0; i < myObj.data.length; i++) {
if (myObj.data[i].symbol == coins[j]) {
document.getElementById("demo").innerHTML +=
myObj.data[i].id + "," + myObj.data[i].name + "," +
myObj.data[i].symbol + "," +
getCoinPrice( myObj.data[i].id ) + "<br>" ;
}
}
}
}
};
xmlhttp.open("GET", "https://api.coinmarketcap.com/v2/listings/", true);
xmlhttp.send();
</script>
</body>
</html>

JavaScript - Calling an 'onClick' function from a For loop loading multiple links

I am in the process of creating a listview from JSON data however, after calling an 'onclick' function from a For loop, the link, which opens up in a new window, loads three URLs into the URL input of the browser. Any idea how I could re-work the below code to just load one link rather that the three based on the below code?
<h3>Links</h3> <br>
<ul class="list">
<div id="timetables"></div>
</ul>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "https://api.myjson.com/bins/qg69t";
var URL_1 = "";
var URL_2 = "";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
URL_1 += arr[i].timetable_1_link;
URL_2 += arr[i].timetable_2_link;
console.log(arr[i].timetable_1_link);
out += '<div>' + arr[i].course + '</div><p>' + arr[i].timetable_1_name + '</p><p>' + arr[i].timetable_2_name + '</p>';
}
document.getElementById("timetables").innerHTML = out;
}
function openLinkInNewWindow_1() {
window.open(URL_1, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
function openLinkInNewWindow_2() {
window.open(URL_2, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
</script>
You can start by refactoring the function that opens the URL to accept a parameter like this:
function openLinkInNewWindow_1(URL) {
window.open(URL, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
Then in the for loop pass the URL along with each link.
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
URL_1 = arr[i].timetable_1_link;
URL_2 = arr[i].timetable_2_link;
console.log(arr[i].timetable_1_link);
out += '<div>' + arr[i].course + '</div><p>' + arr[i].timetable_1_name + '</p><p>' + arr[i].timetable_2_name + '</p>';
}
document.getElementById("timetables").innerHTML = out;
}
This way you only need the one function. Notice also that I removed the + from the URL_1 += line.
Using URL_1+= is culprit here. Every time loops run it appends new string to existing url(s).
So remove += from URL_ variables in your function 'myFunction' and assign values directly by using '=' only.
Updated code is written below
<h3>Links</h3> <br>
<ul class="list">
<div id="timetables"></div>
</ul>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "https://api.myjson.com/bins/qg69t";
var URL_1 = "";
var URL_2 = "";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
URL_1 = arr[i].timetable_1_link;
URL_2 = arr[i].timetable_2_link;
out += '<div>' + arr[i].course + '</div><p>' + arr[i].timetable_1_name + '</p><p>' + arr[i].timetable_2_name + '</p>';
}
document.getElementById("timetables").innerHTML = out;
}
function openLinkInNewWindow_1() {
window.open(URL_1, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
function openLinkInNewWindow_2() {
window.open(URL_2, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
</script>
You can take a look for updated and running code here

No output error when attempting to display json

When the following code executes it's showing no output. Can anyone tell me where I am going wrong?
html file:
<head>
<script type = "text/javascript">function ajax_get_json()
{
var hr = new XMLHTTPRequest();
hr.open("GET","mylist.json",true);
hr.setRequestHeader("Content-type :application/json",true);
hr.onread
ystatechange = function()
{
if(hr.readyState == 4 && hr.status == 200)
{
var data = JSON.parse(hr.responseText);
var results=document.getElementById("results");
results.innerHTML = data.user;
}
}
hr.send(null);
results.innerHTML = "requesting...";
}
</script>
</head>
<body>
<div id="results"></div>
<script type = "text/javascript">ajax_get_json();</script>
</body>
json file:
{ "user":"John", "age":22, "country":"US" }
XMLHTTPRequest() must be XMLHttpRequest(). The JavaScript file looks like:
function request() {}
request();
HTML
<script src="file.js"></script>
With var data = JSON.parse(hr.responseText); you have on object.
Go through the object:
for(var key in obj) {}
and store key and obj[key] in innerHTML to see a result.
Complete JavaScript file:
function request() {
var hr = new XMLHttpRequest();
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText); // object
var results = document.getElementById("results");
results.innerHTML = "";
for(var key in data) {
results.innerHTML += key + " " + data[key] + "<br>";
}
}
}
hr.open("GET", "mylist.json", true);
hr.send();
results.innerHTML = "requesting...";
}
request();
(Please change the title of your question. Be specific!
How to ask)

Need help displaying the contents of a JSON file

http://jsfiddle.net/hbrennan72/0urqaee9/
I have taken a very simple W3Schools JSON example and modified it ever so slightly. I am having trouble displaying just the contents contents of the JSON file. The external JSON file is referenced in the JS but I also copied the contents into the CSS frame on JSFiddle. Any help would be appreciated.
var xmlhttp = new XMLHttpRequest();
var url = "http://schwartzcomputer.com/ICT4570/Resources/USPresidents.json";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].president + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
You need to iterate through arr.presidents.president
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.presidents.president.length; i++) {
out += JSON.stringify(arr.presidents.president[i]) + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
For the XML references, ex. xmlns:xsi, you will need to use bracket notation. You can reference the presidents list objects as you would any JavaSscript object.
Forked jsfiddle
You can display the properties in any format you like.
function myFunction(arr) {
alert(arr.presidents["xmlns:xsi"]);
alert(arr.presidents.president[0].number + ". " + arr.presidents.president[0].name);
...
}
EDIT
I have amended the jsfiddle to create a table. I did not include all the fields you specified, but will get the general idea.

Get JSON data from a file using (JavaScript)

I need to know how can I get json data using JavaScript without using Jquery. I just want to know how to get data only using JavaScript.
My Json file.
{"JsonProjectIDResult":[{"_capacity":15,"_description":"Meeting Room","_dev_default_view":3,"_deviceID":1,"_deviceName":"MobiTech","_deviceTypeID":1,"_projectID":1,"_roomID":2,"_roomName":"Room2","_room_admin_mail":null}]}
My home.html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Get Json</title>
</head>
<body>
<h1>My Home Page</h1>
<div id="results">
<!-- Display Jason Data -->
</div>
<script>
var resultDiv = document.getElementById("results");
var newsURL = "http://localhost:81/testjs/data.json";
var e;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
e = new XMLHttpRequest();
} else {
// code for IE6, IE5
e = new ActiveXObject("Microsoft.XMLHTTP");
}
e.onreadystatechange = function() {
var html = " ";
if (e.readyState == 4 && e.status == 200) {
response = JSON.parse(e.responseText);
if(typeof(e.responseText)==="string") {
d = e.responseText;
} else {
if (typeof(e.responseXML)==="object") {
d = e.responseXML;
};
}
var myData = response['JsonProjectIDResult'];
//Print results
html = myData[0]._capacity+"<br />";
html += myData[0]._description+"<br />";
html += myData[0]._dev_default_view+"<br />";
html += myData[0]._deviceID+"<br />";
html += myData[0]._deviceName+"<br />";
html += myData[0]._deviceTypeID+"<br />";
html += myData[0]._projectID+"<br />";
html += myData[0]._roomID+"<br />";
html += myData[0]._roomName+"<br />";
html += myData[0]._room_admin_mail+"<br />";
resultDiv.innerHTML = html;
}
};
e.open("GET", newsURL, true);
e.send();
</script>
</body>
</html>
After my friends gave me some helpful answer I wondered my code like this. It's working. Now I need to run this as a loop. When every records display using a loop. Can I do it in JavaScript.
<script>
var resultDiv = document.getElementById("results");
var newsURL = "http://localhost:81/testjs/data.json";
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
response = JSON.parse(xmlhttp.responseText);
//here you can manipulate the response as you wish, for example you can:
var myData = response['JsonProjectIDResult'];
// myData now is an array of the json object
var html = '<ul>';
for(var prop in myData ) {
if(myData.hasOwnProperty(prop))
html += '<li>' + prop + ' = ' + myData[prop] + '</li>';
}
html += '</ul>';
//and so on
resultDiv.innerHTML = html;
}
}
xmlhttp.open("GET", newsURL, true);
xmlhttp.send();
</script>

Categories