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

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);

Related

Create Hyperlinks through Json Document

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();

javascript xml reader

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.

Questions to create a nested list retrieved from an XML-file and displayed in xHTML

The objective is to display a list of URLs in an HTML page. The list is retrieved from another file (currently in XML-format).
Validator: What is the proper xHTML mark-up for a list generated by JavaScript and still validate properly?
I assume the reason is that JavaScript-code inside [ul]'s is not accepted. Is this correct? Is there another solution?
The code below does produce the list anticipated, but it creates a warning (pls see below, 2.).
<ul>list A
<li>item A1</li>
<li>item A2</li>
<ul>List B
<li>item B1</li>
<script type="text/javascript">/* <![CDATA[ */
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest(); } // code for IE7+, Firefox, Chrome, Opera, Safari
else
{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } // code for IE6, IE5
xmlhttp.open("GET","/test-code/panorama-list2.xml",false);
// xmlhttp.open("GET","/test-code/panorama-list2.xml",true); //this does not work. xmlDoc is null.
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("item");
for (i=0;i<x.length;i++)
{ document.write('<li class="menu2">'+'<a href="');
document.write(x[i].getElementsByTagName('link')[0].childNodes[0].nodeValue);
document.write('">');
document.write(x[i].getElementsByTagName('description')[0].childNodes[0].nodeValue);
document.write('</li>'); }
//]]></script> //This is line: 136
</ul>
The JavaScript used in the code above is called using the synchronous method and thus creating the Warning:
"An unbalanced tree was written using document.write() causing data from the network to be reparsed. For more information https://developer.mozilla.org/en/Optimizing_Your_Pages_for_Speculative_Parsing
/ Source File: /test-code/index2.htm / Line: 136"
The solution is to use the asynchronous method similar to the code below placed into the section.
The solution is NOT to simply setting 'true' in the function xmlhttp.open (..., ..., true);.
<script type="text/javascript">//<![CDATA[
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest(); } // code for IE7+, Firefox, Chrome, Opera, Safari
else
{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } // code for IE6, IE5
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
xmlDoc = xmlhttp.responseXML;
var txt = "";
var txt1 = "";
var x = xmlDoc.getElementsByTagName("item");
for (i=0;i<x.length;i++)
{
txt = x[i].getElementsByTagName('description')[0].childNodes[0].nodeValue + "<br />";
txt1 = x[i].getElementsByTagName('link')[0].childNodes[0].nodeValue + "<br />";
}
{
document.getElementById("myDiv").innerHTML=txt;
document.getElementById("myDiv1").innerHTML=txt1;
}
}
xmlhttp.open("GET","panorama-list2.xml",true);
xmlhttp.send();
}
//]]></script>
That does take care of the Warning.
I assume a solution would be to combine these 2 examples of code.
That's what I am trying:
The Variables 'txt' and 'txt1' retrieve the last entry of the XML-file.
How do I get all entires as well? The amount of entries varies.
Here is the big question:
How can I create a proper list using the asynchronous method and obtain a result like in the initial code example where the list is generated by stepping through the XML-file?
After all, is there is another, better or simpler solution? The file with data for the list shall not be part of the xHTML mark-up.
At last an actual page using the initial code example. The list is revealed by hovering over the button at top-right: http://www.halo-photographs.com/2011-Cascata-da-Bernina/index.htm (yes, this is my own page)
Thanks for your attention.
you code is an soup..
you need refactor that
now with jquery
in the load the you page
you should put somthing how that
$(document).ready(function(){
BeforePrepareList();
});
function BeforePrepareList()
{
var xmlRequest = XmlHttpRequestResolver();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
var xmlDoc = xmlhttp.responseXML;
// you need parse string response a array or use xslt, the next
// is simple for each
ListSetting(xmlDoc);
}
xmlhttp.open("GET","panorama-list2.xml",true);
xmlhttp.send();
}
function XmlHttpRequestResolver()
{
if (window.XMLHttpRequest)
return xmlhttp=new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
else
return xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
function ListSetting(rawdata)
{
ListPopulate($("_PUT_YOUR_LIST_ID_HERE").get(0), rawdata);
}
function ListPopulate(el, items) {
el.options.length = 0;
if (items.length > 0)
el.options[0] = new Option('All', '');
// THAT IS AN SIMPLE EXAMPLE, CHANGE FOR CREATE tag <a />
$.each(items, function (index,item) {
el.options[el.options.length] = new Option(item.[PROPERTY_A], item.[PROPERTY_B]);
});
}
and .....
more information here
invoke xml and transform http://www.ibm.com/developerworks/xml/library/x-ffox3/index.html
examples de http request http://www.jibbering.com/2002/4/httprequest.html

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);

Get element by tag (with obscure character)

I could use a little help defining the method of getting a tag name when the tag name contains an obscure character.
artist=(x[i].getElementsByTagName("content:encoded")[0].childNodes[0].nodeValue);
I tried and failed with:
artist=(x[i].getElementsByTagName("content" + : + "encoded")[0].childNodes[0].nodeValue);
The full js currently here. i want to also get the contents of the <content:encoded> tag that is also present in every item.
$(document).ready(function() {
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","http://doobox.co.uk/rss/page1/files/blog.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
x=xmlDoc.getElementsByTagName("item");
i=0;
$(document).ready(function() {
displayItem()
});
function displayItem()
{
artist=(x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
title=(x[i].getElementsByTagName("category")[0].childNodes[0].nodeValue);
year=(x[i].getElementsByTagName("link")[0].childNodes[0].nodeValue);
txt="Artist: " + artist + "<br />Title: " + title + "<br />Year: "+ year;
document.getElementById("ShowLatestBlog").innerHTML=txt;
}
$('.back').click(function() {
if (i<x.length-1)
{
i++;
displayItem();
}
});
$('.forward').click(function() {
if (i>0)
{
i--;
displayItem();
}
});
});
Assuming you are dealing with XML:
getElementsByTagNameNS('http://example.com/namespace/of/content', 'encoded');
See also: a reference to the DOM method
when trying to retreive the contents of the xml tag <content:encoded> i dont acctually look for the full tag name like that, Just "encoded" eg:
content=(x[i].getElementsByTagName("encoded")[0].childNodes[0].nodeValue);

Categories

Resources