Read local XML files to parse - javascript

I am trying to make an XML parser, but I am having difficulties loading local files.
The issue being that when I try to load from my local drive it will still look for the file on the same domain. And the error I am receiving is this.
Failed to load resource: the server responded with a status of 404 (Not Found) http://fiddle.jshell.net/Users/username/Documents/catalog.xml
HTML/JS: (http://jsfiddle.net/5dfhz40j/)
<!DOCTYPE html>
<html>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>
<button type="button" onclick="loadDoc()">Load</button>
<br><br>
<table id="myTable"></table>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
xmlFunction(this);
}
};
xhttp.open("GET", "/Users/username/Documents/catalog.xml", true);
xhttp.send();
}
function xmlFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Category</th><th>Title</th></tr>";
var x = xmlDoc.getElementsByTagName("ITEM");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("CATEGORY")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("myTable").innerHTML = table;
}
</script>
</body>
</html>
XML file:
<?xml version="1.0" encoding="UTF-8"?>
<CATALOG>
<ITEM>
<TITLE>TITLE01</TITLE>
<CATEGORY>CAT01</CATEGORY>
<ID>ID01</ID>
</ITEM>
<ITEM>
<TITLE>TITLE02</TITLE>
<CATEGORY>CAT02</CATEGORY>
<ID>ID02</ID>
</ITEM>
<ITEM>
<TITLE>TITLE03</TITLE>
<CATEGORY>CAT03</CATEGORY>
<ID>ID03</ID>
</ITEM>
<ITEM>
<TITLE>TITLE04</TITLE>
<CATEGORY>CAT04</CATEGORY>
<ID>ID04</ID>
</ITEM>
<ITEM>
<TITLE>TITLE05</TITLE>
<CATEGORY>CAT05</CATEGORY>
<ID>ID05</ID>
</ITEM>
</CATALOG>
Expected output:

The error means you are trying to load the file from JSFiddle but it does not exist on JSFiddle and it has no access to your local files because the origin is not the same look up CORS.
Therefore, your code should run fine on your machine and give the desired output if the file exits at that path.
OR
Loaded as an external public file (am using a file from github here):
Run code Snippet
OR
See working Plunkr
var xmlFile = 'https://raw.githubusercontent.com/olayenca/externals/master/XMLParse.xml';
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", xmlFile, true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
xmlFunction(this.response);
}
};
}
function xmlFunction(xml) {
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xml, "text/xml");
var table = "<tr><th>Category</th><th>Title</th><th>Subcategory</th></tr>"; //subcategory heading
var x = xmlDoc.getElementsByTagName("ITEM");
for (var elem of x) {
var titles = elem.getElementsByTagName(
"TITLE")[0].childNodes[0].nodeValue;
var cats = elem.getElementsByTagName("CATEGORY")[0].childNodes[0].nodeValue;
var subCats = elem.getElementsByTagName("SUBCATEGORY").length === 0 ? "..." : elem.getElementsByTagName("SUBCATEGORY")[0].childNodes[0].nodeValue;
table += "<tr><td>" + cats + "</td><td>" + titles + "</td><td>" + subCats + "</td></tr>";
}
document.getElementById("myTable").innerHTML = table;
}
loadDoc();
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
th,
td {
padding: 5px;
}
<table id="myTable"></table>

Related

Display Data in New Tab in Same Browser[Working Code]

I have a Google Script that Displays List of Data from Google Drive and this is what it looks like.
This code is working so perfect you just need index.html and code.gs and here is the code for both of them. (So for those who are using google app script in your site this will help.)
index.html
<!DOCTYPE html>
<html>
<head>
<style>
.my_text
{
font-family: Tahoma;
font-size: 13px;
font-weight: normal;
}
</style>
<base target="_top">
<script>
function displayMessage()
{
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
}
function handleResults(results){
var length=results.length;
var table = document.getElementById("output");
var count = document.getElementById("count");
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|");
count.innerHTML = "Total Records Found : " + length;
table.innerHTML +="</br><a href='"+item[1]+"' target='_blank'>"+item[0]+"</a></br> <B>Owner: </B>" +item[3]+ "</br><B>Last modified: </B>"+item[2]+ "</br> <B>File Size: </B>"+item[4]+"</br>";
}
}
function clearBox(elementID)
{
document.getElementById("output").innerHTML = "";
document.getElementById("count").innerHTML = "";
}
</script>
<style>
table, th, td
{
border: 1px solid black;
}
</style>
</head>
<body>
<div class="container">
<p class = "my_text">Search File : <input type="text" id="idSrchTerm" name="search" class = "my_text">
<input type="button" value="Search Drive" name="submitButton" class = "my_text" onClick="clearBox(); displayMessage();"/>
</div>
<div id = "count" class = "my_text"></div>
<div id ="output" class = "my_text">
</div>
</body>
</html>
code.gs
function doGet(e) { // main function
var template = HtmlService.createTemplateFromFile('index.html');
return template.evaluate().setTitle('Search Drive').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function SearchFiles(searchTerm) {
var searchFor ="fullText contains '" + searchTerm + "'";
var names = [];
var files = DriveApp.searchFiles(searchFor);
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();
var lm = file.getLastUpdated();
var OType = file.getOwner().getName();
var fsize = file.getSize()
var name = file.getName()+"|~|"+file.getUrl()+"|~|"+lm+"|~|"+OType+"|~|"+fsize;
names.push(name);
Logger.log(file.getUrl());
}
return names;
function processForm(searchTerm) {
var resultToReturn;
Logger.log('processForm was called! ' + searchTerm);
resultToReturn = SearchFiles(searchTerm);
Logger.log('resultToReturn: ' + resultToReturn);
return resultToReturn;
}
}
My only target here is how can I display the result in New Window? I mean I will type any string in textbox and click the button then thats it! the output will display in a new window like for example output.html
TYSM for future help.

Displaying data from an XML file

I'm trying to use JavaScript to display data from an XML file. My data isn't being displayed to the web page and I'm not sure why.
Any help/advice would be appreciated. My code is displayed below.
NOTE - I have no experience with XML so be aware that I am completely new to it.
<script>
var xmlData;
function loadXml () {
var filename = "CDLibrary.xml";
var XMLhttp = new XMLHttpRequest();
XMLhttp.open("GET", filename, true);
var ok = true;
try {
XMLhttp.send();
}
catch(err) {
ok = false;
alert ("Database not found");
}
if (ok) {
xmlData = XMLhttp.responseXML;
displayXml(xmlData);
}
}
function displayXml () {
var CdElements;
var CdTitle;
var count;
CdElements = xmlData.getElementsByTagName("CD");
for (count = 0; count < CdElements.length; count=count+1) {
CdTitle = CdElements[count].getElementsByTagName("title");
document.getElementById("output").innerHTML = document.getElementById("output").innerHTML + CdTitle[0].childNodes[0].nodeValue + "</br>";
}
}
</script>
</head>
<body>
<div>
<p id="output">
</p>
<p id="buttons">
<input type="button" id="btnDisplay" value="Display CDs" onclick="loadXml();">
</div>
</body>
<html>
<head><title>Import XML Data</title></head>
<body>
<div>
<p id="output">
</p>
<p id="buttons">
<input type="button" id="btnDisplay" value="Display CDs" onclick="loadXml()">
</div>
<script>
var xmlData;
function loadXml () {
var filename = "CDLibary.xml";
var XMLhttp = new XMLHttpRequest();
XMLhttp.open("GET", filename, true);
var ok = true;
try {
XMLhttp.send();
}
catch(err) {
ok = false;
alert ("Database not found");
}
if (ok) {
xmlData = XMLhttp.responseXML;
displayXml(xmlData);
}
}
function displayXml(xmlDataBase) {
var CdElements;
var CdTitle;
var count;
CdElements = xmlDataBase.getElementsByTagName("CD");
for (count = 0; count < CdElements.length; count=count+1) {
CdTitle = CdElements[count].getElementsByTagName("title");
document.getElementById("output").innerHTML = document.getElementById("output").innerHTML + CdTitle[0].childNodes[0].nodeValue + "</br>";
}
}
</script>
</body>
</html>
You're not using the var xmlData instead you're using a var xmlDataBase. Replace you code to:
CdElements = xmlData.getElementsByTagName("CD");
And since you're using a global var xmlData, it's available inside displayXml function, in this case no need for function displayXml(xmlDataBase) if you use function displayXml() it'll be enough.
Using the w3schools link and changing some information and changing the directory I got it working. There must be an error in the template i was following, thank you all for your time and efforts.
<html>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>
<button type="button" onclick="loadDoc()">Get my CD collection</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", "CDLibrary.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Artist</th><th>Title</th></tr>";
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("performer")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
</html>

DOM updation through javascript not working

I am just trying to prototype a simple functionality using javascript for learning purpose, but the contents within the <p> tag are not updating and I am stuck at this point. My code is as follows:
<!DOCTYPE html>
<html>
<head>
<title> Ajax Search Box </title>
<script>
function LoadList()
{
var searchBox = document.getElementById("txtSearch");
var resultBox = document.getElementById("results");
var searchedChars = "";
var xHttp = new XMLHttpRequest();
searchedChars += searchBox.value;
xHttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200)
{
var xmlContent = this.responseXML;
var nameList = xmlContent.getElementsByTagName("name");
var dispText = "";
for(var i = 0 ; i < nameList.length ; i++)
{
dispText += nameList[i].textContent + "<br/>";
}
resultBox.innerHtml = dispText;
}
};
xHttp.open("GET","AssessorList.xml",true);
xHttp.send();
}
</script>
</head>
<body>
<input id="txtSearch" type="text" placeholder="Search" onkeyup="LoadList();" />
<p id="results">
No Data Available.
</p>
</body>
</html>
Could someone tell me why the innerHtml is not updating? Thanks in advance.
P.S: The code is fetching the data from the xml file as I could see in browser's console, the values being passed to the dispText variable.
<!DOCTYPE html>
<html>
<body>
<input id="txtSearch" type="text" placeholder="Search" onkeyup="LoadList();" />
<p id="results">No data available</p>
<script>
function LoadList() {
var xhttp = new
XMLHttpRequest();
var searchBox =
document.getElementById("txtSearch");
var resultBox = document.getElementById("results");
var searchedChars = "";
searchedChars += searchBox.value;
xhttp.onreadystatechange = function() {
//alert(this.status);
if (this.readyState == 4 && this.status == 200) {
var xmlContent = this.responseXML;
var nameList = searchedChars;
alert(nameList);
var dispText = "";
for(var i = 0 ; i < nameList.length ; i++)
{
dispText += nameList[i] + "<br/>";
}
resultBox.innerHTML = dispText;
}
};
xhttp.open("GET", "ajax.txt", true);
xhttp.send();
} </script>
</body>
</html>
Hope this may help you

Display XML with Javascript

Here's my sample XML code:
<?xml version="1.0" encoding="UTF-8"?>
<entry n="5">
<form type="lemma">hi
<orth xml:lang="syc">ܐܳܐܱܪ</orth>
</form>
<gramGrp>
<gram type="pos">noun</gram>
<gram type="gender">commonGender</gram>
</gramGrp>
<etym>
<lang>Greek</lang>
<mentioned>ἀήρ</mentioned>
</etym>
<form type="inflected" ana="#n_pl">
<orth xml:lang="syc">ܐܰܐܷܪ̈ܰܣ</orth>
</form>
<sense>
<cit type="translation" xml:lang="en">
<quote>air, breeze</quote>
</cit>
</sense>
</entry>
I need to display this in a formatted fashion, depending on the tags. I've followed the code as found at w3schools http://www.w3schools.com/xml/xml_applications.asp, changing the filename and TagName values as necessary. In the end... nothing happens, just a blank screen. I do have a server from which I am running this, btw.
Javascript:
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp);
}
}
xmlhttp.open("GET", "dict.xml", true);
xmlhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Artist</th><th>Title</th></tr>";
var x = xmlDoc.getElementsByTagName("entry");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("lemma")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("sense")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
I will worry about getting all the formatting correct and all the tags represented afterwards, I just need to get it working at all, first.

Dynamically displaying an image from XML with javascript

I'm very new to HTML.
I am trying to load an XML which contains image names and display it in a div dynamically.
I can see the image names but can't assing img a source.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
if (window.XMLHttpRequest) {xmlhttp=new XMLHttpRequest();}
else{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.open("GET","resimler.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
x=xmlDoc.getElementsByTagName("pic");
i=0;
function displayFoto(){
ad=(x[i].getElementsByTagName("ad")[0].childNodes[0].nodeValue);
document.getElementById("showFoto").innerHTML="img/" + ad;}
function next(){
if (i<x.length-1){
i++;
displayFoto();}}
function previous(){
if (i>0){
i--;
displayFoto();}}
</script>
</head>
<body onload="displayFoto()">
<div id='showFoto'><img id='showFoto'></img></div><br>
<input type="button" onclick="previous()" value="<<" />
<input type="button" onclick="next()" value=">>" />
</body>
</html>
Can anyone please guide me?
document.getElementById("showFoto").src="img/" + ad;
this would help you to load image but i dont garanty about rest of the code. You better look for Loader frameworks and jquery.
I agree with Kemal, just give a snipet of your xml and also the id for div and img tag is same, is that something you are unaware of it or just intentional
<script type="text/javascript">
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
xmlDoc = xmlhttp.responseXML;
var Image = "";
x = xmlDoc.getElementsByTagName("IMAGE");
for (i = 0; i < x.length; i++)
{
Image = Image + x[i].childNodes[0].nodeValue + " ";
var res = Image.split(" ");
var ii = res[i];
var img = document.createElement("img");
img.src = ii;
img.width = 150;
img.height = 100;
document.body.appendChild(img);
}
}
}
xmlhttp.open("GET", "ll.xml", true);
xmlhttp.send();
}
</script>
</head>
<body onload="loadXMLDoc()">
</body>

Categories