I am currently working on developing a webpage that is compatible with IE11 and will be installed on multiple users' desktops. The webpage needs to retrieve data from a JSON API and display it.
Users will need to input their unique API keys before clicking a button to view the API data.
I seem to have encountered an issue with my code and I could really use some assistance. The error message displayed in the console reads: "Unable to get property 'addEventListener' of undefined or null reference." It seems like the code is failing to call the API at all.
<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 response we are trying to extract names from looks something like this:
{"data":[{"name":"This is the first name"},{"name":"This is the second name"}]}