Need help displaying the contents of a JSON file - javascript

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.

Related

JSON Parse Javascript Issues

I am using the following to load a local txt file to convert it, the code is directly from W3c schools but the page loads nothing on screen and I have no errors on page or in the inspector. It wont work on MAMP or webserver. I am trying to learn vanilla JS so I don't want to use a library or jquery.
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "array.txt";
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++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
Thanks for your help everyone, the issue was a clash with another function running on the page and the lack of 200 response from the local file.

Having trouble dynamically writing HTML in Chrome

Okay, so I am working on code to display all the images in a folder as a gallery. I've got a PHP script to find all the files in the folder (someone else had written it, and it works just fine):
<?php
$directory = $_REQUEST['folder'];
if (!is_dir($directory)) {
exit('Invalid diretory path');
}
$files = array();
foreach (scandir($directory) as $file) {
if ('.' === $file) continue;
if ('..' === $file) continue;
$files[] = $file;
}
echo json_encode($files);
?>
Now I had a javascript get the json from the php and display it in a grid:
const urlParams = (new URL(document.location)).searchParams;
const folder = urlParams.get('folder');
const gallery = document.getElementById("web_gallery");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
for(var i = 0; i < myObj.length; i++)
{
var write = "<img src='" + folder + "/" + myObj[i] + "' id='gallery_img'>";
console.log(write);
gallery.innerHTML += write;
}
}
};
xmlhttp.open("GET", "toJson.php?folder=" + folder, true);
xmlhttp.send();
This works just fine on Firefox, but it doesn't display anything on Chrome. I looked through several threads here and the one with the most traction seamed to suggest that I should try to use JQuery, so I set that up and wrote this:
$(document).ready(function(){
const urlParams = (new URL(document.location)).searchParams;
const folder = urlParams.get('folder');
var url = "toJson.php?folder=" + folder;
var toWrite = [];
$.get(url, function( data ) {
var images = JSON.parse(data);
for(var i = 0; i < images.length; i++)
{
toWrite.push("<img src='" + folder + "/" + images[i] + "' id='gallery_img'>");
//$( "#web_gallery" ).append( write ); // Had this here before, but tried to move it down to after it's done.
}
}).done(function()
{
for(var i = 0; i < toWrite.length; i++)
{
$("#web_gallery").append(toWrite[i]);
}
});
});
Someone else suggested that you shouldn't do so many append requests so I changed it to:
$(document).ready(function(){
const urlParams = (new URL(document.location)).searchParams;
const folder = urlParams.get('folder');
var url = "toJson.php?folder=" + folder;
var write = "";
$.get(url, function( data ) {
var images = JSON.parse(data);
for(var i = 0; i < images.length; i++)
{
write += "<img src='" + folder + "/" + images[i] + "' id='gallery_img'>\n";
}
}).done(function()
{
setTimeout(function () {
$("#web_gallery").append(write);
}, 1500);
});
});
All of these work fine in Firefox, but not a single one of them work in Chrome, and I'm not sure why. It seems to have to do with the time and speed of writing to the page, I think.
Append the image element with the createElement method.
var image = document.createElement('img');
image.src = imageFilePath;
$(image).appendTo("#web_gallery");

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

How to fetch child node values from xml file using 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>

How to print xmlhttp response?

I am getting some information from database, this information is getting back into JSON format now I need to print this JSON information. But my code is not working getCountryDetails.php is php file for interacting with the database. Following code is the script, When I click the button It intersects with database.
<script type="text/javascript">
$(document).ready(function() {
$("#quickSearch").click(function(){
var countries = [];
$.each($("#select-choice-1 option:selected"), function(){
countries.push($(this).val());
});
if (countries == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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) {
//myFunction(xmlhttp.responseText);
myFunction(xmlhttp.responseText);
}
}
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
xmlhttp.open("GET","webservices/getCountryDetails.php?q="+countries,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>
Firstly, countries will never be an empty string, you've defined it as an array
var countries = [];
...
if (countries == "") { // always fail
secondly, you can't concantenate an array into a string, and XMLHttpRequest doesn't accept arrays
xmlhttp.open("GET","webservices/getCountryDetails.php?q=" + countries, true);
Thirdly, you seem to be using jQuery, so why not use it as it does accept an array
$.ajax({
url : 'webservices/getCountryDetails.php',
data : countries
}).done(myFunction);

Categories