0

I am trying to create an IE11 compatible webpage which will sit on a few users desktops, which will grab some data from a JSON API and display it.

The user will type in their individual API key before pressing a button, revealing the API data.

Could you please help where my code has gone wrong? The error message I get from the console is: "Unable to get property 'addEventListener' of undefined or null reference. " So it looks like it is not even making the call to the API.

<script>
var btn = document.getElementById("btn");
var apikey = document.getElementById("apikey").value

btn.addEventListener("click", function() {
  var ourRequest = new XMLHttpRequest();
  ourRequest.open('GET', 'http://example.example?&apikey=' + document.getElementById("apikey").value);
  ourRequest.onload = function() {
    if (ourRequest.status >= 200 && ourRequest.status < 400) {
    var ourData = JSON.parse(ourRequest.responseText);
    document.getElementById("title").textContent = ourData.data[0]["name"];
}}}
);
</script>

.

<body>
 Enter API key: <input type="text" id="apikey">
 <button id="btn">Click me</button>
 <p id="title"></p>
</body>

The API data which I am trying to just extract the name from, looks something like this:

{"data":[{"name":"This is the first name"},{"name":"This is the second name"}]}
  • 1
    "Could you please help where my code has gone wrong?" — What makes you think something has gone wrong? You need to provide a *clear problem statement*. Do debugging. Look for error messages in the console. Check the network request and response in the Network tab of the developer tools. etc. – Quentin Oct 30 '19 at 11:34
  • Sorry I am new to this, I added some extra detail – frustratedbutoptimistic Oct 30 '19 at 11:46
  • Duplicate: https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element – Quentin Oct 30 '19 at 11:58

1 Answers1

-1

It's likely that you're including the Javascript in the page before the HTML. As Javascript is executed as soon as the browser reaches it, it will be looking for the #btn element which will not have been rendered yet. There are two ways to fix this:

  1. Move the Javascript to the bottom of the <body> tag, making it run after the HTML has been output to the page.
  2. Wrap the Javascript in a DOMContentLoaded event, which will defer the script until the page has finished loading. An example is as follows:
window.addEventListener('DOMContentLoaded', function() {
    var btn = document.getElementById('btn');
    var apikey = document.getElementById("apikey").value;

    [...]
});
Daniel Samuels
  • 816
  • 8
  • 24