0

I'm trying to rebuild some stuff I used in python but I'm finding it very tricky to pull data from an API link.

below is the function I'm trying to use to call the API and then get the data I want out of the XML file that the link 'https://api.bmreports.com/BMRS/FUELINSTHHCUR/v1?APIKey=&ServiceType=XML' returns however at the moment I'm struggling to get anything back at all

function GetXML(){
        var request = new XMLHttpRequest();
        request.open("GET", 'https://api.bmreports.com/BMRS/FUELINSTHHCUR/v1?APIKey=&ServiceType=XML', false);
        request.send();
        var xml = request.responseXML;
        var fuel = xml.getElementsByTagName("fuelType");
        for(var i = 0; i < users.length; i++) {
            var fuel = fuel[i];
            var fuelnames = user.getElementsByTagName("fuelType");
            for(var j = 0; j < fuelnames.length; j++) {
                alert(fuelnames[j].childNodes[0].nodeValue);
            }
        }
    }
Ramana V V K
  • 1,245
  • 15
  • 24
adam Wadsworth
  • 774
  • 1
  • 8
  • 26
  • You need to parse the XML. jQuery (which you've tagged, but not used) has a handy way to do this, while vanilla javascript is a little more complicated (unless it's changed in latest browsers). See https://stackoverflow.com/questions/7949752/cross-browser-javascript-xml-parsing – freedomn-m Apr 25 '18 at 14:46
  • Possible duplicate of [Cross-Browser Javascript XML Parsing](https://stackoverflow.com/questions/7949752/cross-browser-javascript-xml-parsing) – freedomn-m Apr 25 '18 at 14:47
  • @freedomn-m I understand i need to Parse the XML but i don't know where i put the URL link all the examples on the web seem to leave that out – adam Wadsworth Apr 25 '18 at 14:54
  • What does this give you? `console.log(request.responseXML);` You've already put the "url link" in – freedomn-m Apr 25 '18 at 15:09
  • @freedomn-m i get this in the console [object XMLDocument]{activeElement: , alinkColor: "#0000ff", all: undefined, anchors: HTMLCollection {...}, applets – adam Wadsworth Apr 25 '18 at 15:30

1 Answers1

0

try this example:

var request = new XMLHttpRequest();
request.open("GET", 'https://api.bmreports.com/BMRS/FUELINSTHHCUR/v1?APIKey=&ServiceType=XML', true);
request.responseType = 'document';
request.overrideMimeType('text/xml');
request.onload = function () {
  if (request.readyState === request.DONE) {
    if (request.status === 200) {
      console.log(request.responseXML);
    }
  }
};
request.send(null);
Minh
  • 51
  • 4
  • this is what i get in the console whey trying this No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. – adam Wadsworth Apr 25 '18 at 15:26
  • See https://stackoverflow.com/questions/20035101/why-does-my-javascript-get-a-no-access-control-allow-origin-header-is-present – freedomn-m Apr 25 '18 at 15:43
  • yes I think you will need to add the APIKey value in the url – Minh Apr 25 '18 at 15:50