javascript xml reader - javascript

I will keep this very short:
I'm trying to make a loop through an xml-document for a gallery. I got a script that should work, but doesn't. Can anyone please tell me where I did wrong?
I didn't want to make this longer because the problem is simple and have been pondering over this since yesterday and this is the closest I get.
I want to loop through the xml-file and print out "path" and "file" first and most. I'm building a gallery and thought that the best way to save all the data for the images was an xml-file, but now I can't get it to loop correctly. In the script I made the page print out both x and i, which resulted with x being 1 and i being 0, hence it hasn't worked through the for-loop at all as I see it.
Any help would be appreciated, because I'm stuck. Been trying so many solutions that my head is spinning and I can't get any further without a nudge in the right direction.
The html/javascript:
<script type="text/javascript">
function displayResult()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","../gallery/gallery.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
x=xmlDoc.getElementsByTagName("session");
for (i=0;i<x.length;i++)
{
img = "<img src='";
path = (x[0].getElementsByTagName("path")[0].childNodes[0].nodeValue);
file = (x[i].getElementsByTagName("file")[i].childNodes[0].nodeValue);
end = "' /><br />";
name = (x[i].getElementsByTagName("name")[i].childNodes[0].nodeValue);
txt = "x:" + x.length + "| i " + i + "<br />" + img + path + file + end + name + "<br />";
document.getElementById("content").innerHTML = txt;
//document.write(txt);
}
}
</script>
</head>
<body onload="displayResult()">
<div id='content'></div>
</body>
</html>
xml-file:
<gallery>
<session>
<path>../gallery/beauty/</path>
<item>
<file>_DSC2331.jpg</file>
<name>Picture 1</name>
</item>
<item>
<file>_DSC2339.jpg</file>
<name>Picture 2</name>
</item>
<item>
<file>_DSC2350.jpg</file>
<name>Picture 3</name>
</item>
<date>2011-08-03</date>
</session>
</gallery>

If I can make some suggestions:
Use the var keyword within functions to make those variables local to that function. The code you have at the moment would set values in the global namespace, which is often considered bad practice (e.g. you could overwrite other people's variables, or other people could overwrite yours). Also declare your variables at the start of a function, as they will be hoisted there anyway.
Split your code up into more meaningful functions. This way they become easier to read and often then become more reusable.
Make sure you loop through items as well as sessions.
Consider using a Javascript framework like jQuery. They can often simplify the code you have to write, and you will usually end up writing less code yourself.
.
<html>
<head>
<script type="text/javascript">
function loadDoc(url) {
var xmlhttp = null;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", url, false);
xmlhttp.send();
return xmlhttp.responseXML;
}
function getContent(sessions) {
var items = null,
i = 0,
j = 0,
img = "",
path = "",
file = "",
end = "",
name = "",
txt = "";
for (i = 0; i < sessions.length; i++) {
items = sessions[i].getElementsByTagName("item");
path = sessions[i].getElementsByTagName("path")[0].childNodes[0].nodeValue;
for (j = 0; j < items.length; j++) {
img = "<img src='";
file = items[j].getElementsByTagName("file")[0].childNodes[0].nodeValue;
end = "' /><br />";
name = items[j].getElementsByTagName("name")[0].childNodes[0].nodeValue;
txt += "session[" + i + "] item[" + j + "]<br />" + img + path + file + end + name + "<br />";
}
}
return txt;
}
function displayResult()
{
var xmlDoc = loadDoc("../gallery/gallery.xml");
var sessions = xmlDoc.getElementsByTagName("session");
var txt = getContent(sessions);
document.getElementById("content").innerHTML = txt;
}
</script>
</head>
<body onload="displayResult()">
<div id='content'></div>
</body>
</html>

It would seem to me that you want to show all items.
Yet you loop over 'session', of which there is only one.
So at best you will get only 1 picture this way..
You probably want to loop over xmlDoc.getElementsByTagName("item") and still use the session one to have access to the path.

Related

Unable to get .xml file to load in to .php file using html + javascript

I don't need anything fancy on this. I'm loading a Q&A page. The Q&A I want on a seperate file so I can just update the file and it will update the page the next time it's loaded by someone.
I created a file "faq.xml" and am trying to load that in to my faq.php file.
<p id="xmlp" class="content" style="text-align: center">
<!-- XML should go here -->
</p>
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
myFunction(this);
xmlhttp.open("GET", "faq.xml", true);
xmlhttp.send();
}
function myFunction(xml) {
var x, i, xmlDoc, table;
xmlDoc = xml.responseXML;
table = "<tr><th>Question</th><th>Answer</th></tr>";
x = xmlDoc.getElementsByTagName("faqs")
for (i = 0; i < x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("question")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("answer")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("xmlp").innerHTML = table;
}
</script>
For whatever reason, it's not loading anything. The XML file currently has this...
<?xml version="1.0" encoding="UTF-8"?>
<faqs>
<question>When do you fly?</question>
<answer>We fly at sunrise weather permitting. Flights are more peaceful and the winds are great. We even fly low enough to have a conversation with those less fortunate on the ground. People tend to hang around at launch and landings to see what it’s all about.</answer>
</faqs>
Any suggestions? I'm new to XML (this is my first one).
Thank you in advanced.
I put an alert in to ensure the js was getting started and it did function.
<script>
loadXMLDoc();
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
alert();
myFunction(this);
xmlhttp.open("GET", "faq.xml", true);
xmlhttp.send();
}
Still not sure where the hold up is.
I did more testing and I think I found where at least something is wrong...
<p id="xmlp" class="content" style="text-align: center">
<!-- XML should go here -->
</p>
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
myFunction(this);
xmlhttp.open("GET", "faq.xml", true);
xmlhttp.send();
}
function myFunction(xml) {
var x, i, xmlDoc, table;
xmlDoc = xml.responseXML;
table = "<tr><th>Question</th><th>Answer</th></tr>";
alert("This one works");
x = xmlDoc.getElementsByTagName("faqs")
alert("This one does not work");
for (i = 0; i < x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("question")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("answer")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("xmlp").innerHTML = table;
}
</script>
This is a basic example of loading an xml file via AJAX from https://www.w3schools.com/js/tryit.asp?filename=tryjs_ajax_xml:
<body onLoad="loadXMLDocument('someXMLfile.xml')">
<p>
<b>Status:</b> <span id="statusInfo"></span>
</p>
<p>
<b>Status text:</b><span id="statusTextInfo"></span>
</p>
<p>
<b>Response:</b> <span id="xmlContent"></span>
</p>
<script>
function loadXMLDocument(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('statusText').innerHTML = this.status;
document.getElementById('statusTextInfo').innerHTML = this.statusText;
document.getElementById('xmlContent').innerHTML = this.responseText;
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
</script>
</body>
This will load an XML file into Javascript.
Though as I mentioned, if you're getting to grips with AJAX, PHP and XML all at once
the straightforward way might be to make an AJAX call to PHP and process the xml using a php function on the server.
The 4/200 status codes make AJAX debugging a little easier.

javascript json parse from URL

UPDATED:
I'm trying to parse a response from a URL but have no idea if I'm doing it correctly.
The URL returns the following JSON:
{"make":"truck","date":"23 July 2009","colour":"pink"};
If i replace var newtext = xhttp.responseText; with
var newtext = '{"make":"truck","date":"23 July 2009","colour":"pink"}';
it works but as soon as i go back to the xhttp.responseText it just shows a blank page.
The code I'm using is:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
xhttp.open("GET", "https://url.com", false);
xhttp.send();
var newtext = xhttp.responseText;
var obj = JSON.parse(newtext);
document.getElementById("demo").innerHTML =
obj.make + "<br>" +
obj.colour + "<br>" +
obj.date;
</script>
</body>
</html>
You haven't defined your variable xhttp, but you are trying to call functions on it. This is resulting in the Uncaught ReferenceError error and causing the rest of the code not to run. To create an XMLHttpRequest object as you appear to be trying to do, put this at the top of your script.
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// the object actually exists here now so the functions can be called on it
xhttp.open("GET", "https://url.com", false);
xhttp.send();
...
Then you can continue on with the rest of your code, assured that your xhttp object has been initialized.
I don't normally recommend using w3schools, but the above code was copied from http://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asp

Javascript failure to generate divs that include XML info. (xml beginner)

I am trying to create a script that will generate divs depending on the information of the XML file that I desire. The issue is that my script does not work at all. What I did was to find the code on w3schools.org and modified it a bit to match what I wanted it to do.
The results:
<script type="text/javascript">
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","products.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var size=0;
var i=0;
var x=xmlDoc.getElementsByTagName("honey");
var y=x.length;
var final=null;
function gethoney()
{
for (i < y)
{
a1='<div style="height:200px;width:300px;float:left;background-color:#FFF5CC;opacity:0.7;text-align:center;">';
a2='<p><b>';
a3=(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue);
a4='<br>';
a5=(x[i].getElementsByTagName("price")[0].childNodes[0].nodeValue);
a6='</br></b></p>';
a8='</div>';
a9='<div style="height:200px;width:20px;float:left;"></div>';
a10='<div style="height:200px;width:100px;float:left;">';
a11=(x[i].getElementsByTagName("image")[0].childNodes[0].nodeValue);
a12='</div>';
final=final + a1 + a2 + a3 + a4 + a5 + a6 + a8 + a9 + a10 + a11 + a12;
size=size+300;
i=i+1;
}
document.getElementById("mainbody").style.height=size;
size=size-20;
document.getElementById("products").style.height=size;
document.getElementById("products").innerHTML=final;
}
</script>
Using final in order to save every single div doesn't seem like an ideal way to me but I did it anyway.
and the XML is this:
<?xml version="1.0" encoding="windows-1252"?>
<honey>
<name>one</name>
<price>3</price>
<image><img src=""></img></image>
<disc>This is a honey</disc>
</honey>
<honey>
<name>one</name>
<price>3</price>
<image><img src=""></img></image>
<disc>This is a honey</disc>
</honey>
etc etc
I tried to find info about this but without any luck. Could anyone point out what I am doing wrong and suggest improvements/corrections? Also, it would be appreciated if someone could write down a way to generate the divs without using final to save them and then innerHTML.
1) Your xml file is not xml.
2) Change this:
xmlDoc=xmlhttp.responseXML;
to this:
xmlDoc = xmlhttp.responseXML.documentElement;
2)
for (i < y)
That's an error.
4) You define a function called gethoney() that you never call. But you shouldn't call that function until you can get something like this to work:
console.log("==>" + xmlDoc[0].getElementsByTagName("name")[0].childNodes[0].nodeValue);

document.write(xmlDoc..) get text from XML file

I'm trying to read a specific line out of an XML document. It works when 'calling' them directly, but I don't know how to do it with underlying lines.
Here's the XML file:
http://rapidimg.org/server/files/50a55cca752a9ciUnOM.png
Load XML:
// load xml file
if (window.XMLHttpRequest)
{
xhttp = new XMLHttpRequest();
}
else
{
// IE 5/6
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "vragen.xml", false);
xhttp.send();
xmlDoc = xhttp.responseXML;
Now how do I make it so that in a for loop only answer A is shown? I got the for loop, but how do I continue?
for(i=0; i < totalQuestions; i++)
{
document.write("<br />");
document.write((i + 1) + ") " +
xmlDoc.getElementsByTagName("vragen")[i].childNodes[1].textContent +
"<br />");
document.write(xmlDoc.getElementsByTagName("vragen")[i].childNodes[2].childNodex[1].textContent);
//It has to read: vragen/antwoorden/a
}
I want it to show the first answer no matter what question I'm in.

Getting a file from a server using Javascript

So, I wrote some JavaScript to grab an xml file from my desktop and display it on an html page. However, I now have added my xml file to a webserver (mongoose). I want to call the file from that server, but whenever I call the file from the server it dosen't work, but when I call it from my desktop it loads fine.
I want to swap
xmlhttp.open("GET","Devices.xml",false);
with
xmlhttp.open("GET","http://localhost:8080/Devices.xml",false);
Here is the code
<html>
<head>
<script type="text/javascript">
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","Devices.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
// the <Device> list
x = xmlDoc.getElementsByTagName('Device');
// make a function that extracts the attributes out of a Node
function getDeviceAttributes(dvc) {
var name = dvc.getAttribute("name");
var uuid = dvc.getAttribute("uuid");
var id = dvc.getAttribute("id");
return "<p>name: " + name + "<br> uuid: " + uuid + "<br> id: "+ id + "</p>";
}
// loop through the list
// assuming order doesn’t matter
var txt = '';
for (var i = x.length; i--;) {
txt += getDeviceAttributes(x[i]);
}
//show the result on page load
window.onload = function() {
document.getElementById("showDevices").innerHTML = txt;
};
</script>
</head>
<body>
<div id='showDevices'></div>
</body>
</html>
Does anyone know how I can get this to work?
I have been told to use AJAX and Jquery, but I have no idea how to or even where to begin.
It looks like you are repeating a lot of work that jQuery can do for you. Check out the documentation for the Get request method
So something like this:
$.get('http://localhost:8080/Devices.xml', function(data) {
$('#showDevices').html(data);
});
I believe that is the jQuery for what you are trying to do. Hope that helps.
-Charlie
Just some generic advice, you could also use the .load() ajax function if you didn't want to parse the response and this:
window.onload = function() {
document.getElementById("showDevices").innerHTML = txt;
};
can be done in jQuery like this $("#showDevices").html(txt);

Categories

Resources