Skip to content
Advertisement

XML response text is undefined

I am making a call to an external server and am getting a valid response back with data. If I dump that data into console.log() I can see the data that I’m looking for. However the returned data is XML and if I try and use the getElementsByTagName method on the response text I get the error Uncaught TypeError: searchResults.getElementsByTagName is not a function. I checked and searchResults is undefined, which I’m assuming is my problem, I’m just not sure how to fix it.

function getBggData() {
  var searchTerm = document.getElementById("searchTerm").value;
  // console.log("Search Term = " + searchTerm);
  var httpURL = "https://www.boardgamegeek.com/xmlapi2/search?type=boardgame,boardgameexpansion&query=" + searchTerm
  // console.log("URL used is = " + httpURL);
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      displayData(this);
    }
  };
  xhttp.open("GET", httpURL, true);
  xhttp.send();
};

function displayData(xml) {
  var i;
  var searchResults = xml.responseText;
  console.log(searchResults.type);
  console.log(searchResults);
  var table = "<tr><th>Game</th><th>Year Released</th></tr>";
  var x = searchResults.getElementsByTagName("item");
  document.getElementById("resultsHeader").innerHTML = "Search Results = " + x + " items.";
  document.getElementById("searchResults").innerHTML = table;
};

Advertisement

Answer

you can do like this,

var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xml,"text/xml");
console.log(xmlDoc.getElementsByTagName("title")[0]);

here we are parsing the xml and getting it to the variable xmlDoc

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement