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.
Related
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.
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
I apologize in advance if this is a really simple request that has already been answered and I am just too unfamiliar with javascript to understand.
I would like to create a json catalog that displays on an HTML page as a table and I would like for one of the cells to be a hyperlink, but I can't figure out how to do that.
Here is my json script:
"beer": [{
"name": "NAME",
"type": "TYPE",
"company": "BREWERY",
"website": "WWW.SITE.COM",
"price": 6.00
}],
and this is my HTML script
<script>
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","catalog.json",false);
xmlhttp.send();
json=JSON.parse(xmlhttp.responseText);
document.write("<table class=table table-bordered>");
var x=json.beer;
for (i=0;i<x.length;i++)
{
document.write("<tr><td>");
document.write(x[i].name);
document.write("</td><td>");
document.write(x[i].type);
document.write("</td><td>");
document.write(x[i].company);
document.write("</td><td>");
document.write(x[i].website);
document.write("</td><td>$");
document.write(x[i].price.toFixed(2));
document.write("</td></tr>");
}
document.write("</table>");
</script>
Can anyone help with this
First off, don't use document.write. If called after the page is done loading, it will erase the entire page. Better to use DOM methods to add new elements.
Second, AJAX is (supposed to be) asynchronous, why are you passing false to .open()? (P.S. I doubt anyone is gonna be accessing this site with IE5/6, so you can lose the new ActiveXObject)
// In 2014, this is all that's really needed
var xhr = new XMLHttpRequest;
// The callback to run when the request is done
xhr.onload = function(){
// readyState 4 means the request is done, and 200 is HTTP OK
if(xhr.readyState === 4 && xhr.status === 200){
var json = JSON.parse(xhr.responseText),
// The data we want to loop over
x = json.beer,
// This is how to make a new element
table = document.createElement('table');
// Set the classes
table.className = "table table-bordered";
// Loop over your data
for(var i = 0; i < x.length; i++){
// Create the HTML for this row
var row = '<tr>' +
'<td>'+x[i].name+'</td>' +
'<td>'+x[i].type+'</td>' +
'<td>'+x[i].company+'</td>' +
// For a hyperlink, just use an `<a>` tag
'<td>'+x[i].website+'</td>' +
'<td>'+x[i].price.toFixed(2)+'</td>'+
'</tr>';
// Let's just simply append to the table's innerHTML
table.innerHTML += row;
}
// Add the table to the page
document.body.appendChild(table);
}
};
// This defaults to being *asynchronous*
xhr.open("GET","catalog.json");
// Start the request
xhr.send();
I wonder whether someone can help me please.
I've put together this page, which will give the user functionality to load markers with the selection or deselection of checkboxes. They will then be able to click on these markers which in turn shows the nearest POI within a given radius.
The problem I'm having is with loading the xml at lines 143-145 which are:
downloadUrl("loadmylocations.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker")
Firefox tells me that the error is that the 'xml is undefined'. I think I know why and that's because I'm using this code to pull data for the POI's.
var radius = document.getElementById('radiusSelect').value;
var searchUrl = 'searchsites.php?siteosgb36lat=' + center.lat() + '&siteosgb36lon=' + center.lng() + '&radius=' + radius;
downloadUrl(searchUrl, function(data) {
var xml = parseXml(data);
So they clash, because I define the XML at the end of the script differently, these being
loadmylocations.php
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
searchsites.php
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {}
Could someone perhaps tell me please how I can change so that I can pull the two sets of data wihtin the same script without them clashing.
Many thanks and kind regards
I did some work around this, and through trial and error I discovered that I could load the information for the 'loadmylocations' script as the 'searchsites' script i.e. var xml = parseXml(data); rather than var xml = data.responseXML;.
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.