aaron lilly
aaron lilly

Reputation: 274

XML API Calls with HTML and Javascript

I want to make my inner html contain the result of an API call when there is only one item in the XML doc.

Currently I have only figured out (thanks to W3) how to call when multiple Items exist in the XML.

<!DOCTYPE html>
<html>
<style>
table,th,td {
  border : 1px solid black;
  border-collapse: collapse;
}
th,td {
  padding: 5px;
}
</style>
<body>

<h1>The XMLHttpRequest Object</h1>

<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", "https://aaronlilly.github.io/PokeApp/cd_catalog.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("ARTIST")[0].childNodes[0].nodeValue +
    "</td><td>" +
    x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
    "</td></tr>";
  }
  document.getElementById("demo").innerHTML = table;
}
</script>

</body>
</html>

the above works, but if i change the "GET" to an XML doc with only one item -

<?xml version="1.0" encoding="UTF-8"?>
<CATALOG>
  <CD>
    <TITLE>Empire Burlesque</TITLE>
    <ARTIST>Bob Dylan</ARTIST>
    <COUNTRY>USA</COUNTRY>
    <COMPANY>Columbia</COMPANY>
    <PRICE>10.90</PRICE>
    <YEAR>1985</YEAR>
  </CD>
</CATALOG>

(data from https://aaronlilly.github.io/PokeApp/cd_catalog2.xml)

I can't get it to work if I change the for loop to an if statement Any suggestions?

Upvotes: 0

Views: 2618

Answers (2)

Carlos
Carlos

Reputation: 304

I don't know if a I exactly understand your problem, but you can insert a if to check if is a array or not, like it:

if(typeof x[0] == 'undefined')
   x = [x];

Using your function, the complete code would be:

function myFunction(xml) {
  var i;
  var xmlDoc = xml.responseXML;
  var table="<tr><th>Artist</th><th>Title</th></tr>";
  var x = xmlDoc.getElementsByTagName("CD");
  if(typeof x[0] == 'undefined')
    x = [x];
  for (i = 0; i <x.length; i++) { 
    table += "<tr><td>" +
    x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
    "</td><td>" +
    x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
    "</td></tr>";
  }
  document.getElementById("demo").innerHTML = table;
}

Upvotes: -1

0xnoob
0xnoob

Reputation: 1057

If you open up your linked XML file in the browser, you will get an error:

error on line 2 at column 6: XML declaration allowed only at the start of the document

Remove the first empty line in your file, so that <?xml version="1.0" encoding="UTF-8"?> is at the very top.

Upvotes: 3

Related Questions