Search code examples
javascriptgoogle-chromexmlhttprequest

Why does my XMLHttpRequest return 3 errors but works?


I'm working on a Chrome extension that uses a XMLHttpRequest in order to make use of an API. Here is the code I have so far:

myscript.js:

function httpGetAsync(theUrl) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
          var bitcoinInfo = JSON.parse(xmlHttp.responseText);
          output.innerHTML += bitcoinInfo.bpi.USD.rate;
          tabTitle.innerHTML += bitcoinInfo.bpi.USD.rate;
    }
    xmlHttp.open("GET", theUrl, true);
    xmlHttp.send(null);
};
var output = document.getElementsByClassName('bit-price')[0];
var tabTitle = document.querySelector('title');
document.addEventListener('DOMContentLoaded', httpGetAsync('http://api.coindesk.com/v1/bpi/currentprice.json'));

Issue: Code works, it displays the price but I don't understand why I get the following 3 errors in the inspector console and how can I improve my code in order to stop them from showing in the console:

Uncaught TypeError: Cannot read property 'bpi' of undefined
    at XMLHttpRequest.xmlHttp.onreadystatechange (myscript.js:6)
    at httpGetAsync (myscript.js:9)
    at myscript.js:14

Uncaught TypeError: Cannot read property 'bpi' of undefined
    at XMLHttpRequest.xmlHttp.onreadystatechange (myscript.js:6)

Uncaught TypeError: Cannot read property 'bpi' of undefined
    at XMLHttpRequest.xmlHttp.onreadystatechange (myscript.js:6)

What have I tried: I've searched on SO and Google but unfortunately didn't find anything that could help me fix this issue I currently have.


Solution

  • You are missing { and } inside the if statement

    function httpGetAsync(theUrl) {
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
              var bitcoinInfo = JSON.parse(xmlHttp.responseText);
              output.innerHTML += bitcoinInfo.bpi.USD.rate;
              tabTitle.innerHTML += bitcoinInfo.bpi.USD.rate;
            }
        }
        xmlHttp.open("GET", theUrl, true);
        xmlHttp.send(null);
    };