Javascript gets xml but when it loops it emptys the page

Hi,

I’m making a page which gets the contents of an xml file and creates a table and populates it. The problem is when it loops around it seems to strip everything from the page HTML, HEAD, BODY tags and everything inside of those and just puts the value of the elements from the xml file onto the page.

My question is, am I able to perform this loop and keep the rest of the contents of the page intact?

I’ve been trying for most of the day and I can’t get this working. Any help would be appreciated.


<script type="text/javascript">

setInterval ( "refresh()", 5000 );

function refresh()
{
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","status.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML; 
var x=xmlDoc.getElementsByTagName("DEVICE");
for (i=0;i<x.length;i++)
  { 
   document.write("<tr><td>");
  document.write(x[i].getAttribute("ID"));  
  document.write("</td>");
   document.write("<td>");
  document.write(x[i].getElementsByTagName("NAME")[0].childNodes[0].nodeValue);
  document.write("</td>");
   document.write("<td>");
  document.write(x[i].getElementsByTagName("ID")[0].childNodes[0].nodeValue);
    document.write("</td>");
   document.write("<td>");
  document.write(x[i].getElementsByTagName("DESIGNATION")[0].childNodes[0].nodeValue);
    document.write("</td>");
   document.write("<td>");
  document.write(x[i].getElementsByTagName("LOCATION")[0].childNodes[0].nodeValue);
    document.write("</td>");   
	document.write("<td>");
  document.write(x[i].getElementsByTagName("SUBJECT")[0].childNodes[0].nodeValue);
  document.write("</td>");
  	document.write("<td>");
  document.write(x[i].getElementsByTagName("SUBJECT_ID")[0].childNodes[0].nodeValue);
  document.write("</td>");
  	document.write("<td>");
  document.write(x[i].getElementsByTagName("OTHER")[0].childNodes[0].nodeValue);
  document.write("</td>");
  	document.write("<td>");
  document.write(x[i].getElementsByTagName("RATING")[0].childNodes[0].nodeValue);
  document.write("</td>");
  	document.write("<td>");
  document.write(x[i].getElementsByTagName("NOTES")[0].childNodes[0].nodeValue);
  document.write("</td>");
    document.write("</tr>"); 
  }

}
</script>

When you use document.write, if the page has finished loading the document.write will write the content to a new page and not to the current one.

So, instead of writing out the raw HTML code, you should create elements and add those instead to the page.
For example:


function newTD(value) {
    var td = document.createElement('td');
    td.appendChild(document.createTextNode(value));
}
var table = document.getElementById('status');
var tr = document.createElement('tr');
tr.appendChild(newTD(x[i].getAttribute("ID")));
...
table.appendChild(tr);