Tips for retrieving data from an external JSON API upon click without using the fetch method

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"}]}

Answer №1

One common issue occurs when the Javascript code is placed before the HTML in the page structure. Since Javascript executes immediately when encountered by the browser, it may try to access elements like #btn that have not yet been rendered. To resolve this issue, consider the following solutions:

  1. Reposition the Javascript code to the end of the <body> tag so that it runs after the HTML content is fully loaded.
  2. Enclose the Javascript within a DOMContentLoaded event listener to delay its execution until the entire page has finished loading. An example implementation is shown below:
window.addEventListener('DOMContentLoaded', function() {
    var btn = document.getElementById('btn');
    var apikey = document.getElementById("apikey").value;

    [...]
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I implement a page switch in vuejs by clicking on a name in a table list?

I'm currently working on a list page in VueJS and facing some challenges. Here is the code snippet: <template> <vue-good-table :columns="columns" :rows="row" :search-options="{ ...

Utilize AngularJS's nested ng-repeat to showcase information from two distinct JSON strings simultaneously

I am dealing with two different JSON strings from databases. [{ sport: football, sportid: 1 },{ sport: tennis, sportid: 2 },{ sport: golf, sportid: 3 },{ sport: swimming, sportid: 4 }] and [{ personid: 1, name: ...

Tips for transferring information between two distinct pages utilizing the jQuery POST technique

I'm dealing with two PHP files called card_process.php and payment.php. My goal is to transfer data from the cart_process page to the payment page. Here's a snippet of the code: In cart_process.php: $paynow = "<button type='submit' ...

Is it feasible to use multiple Locales within a single MessageFormat instance?

I am facing an issue with formatting JSON data in different locales. Here is an example of the JSON data: { "value": 946.2, "description": "The value is $946.20." } When I try to use MessageFormat for JUnit testing, I ...

Using QML to assign global properties by invoking imported JavaScript functions

Utilizing the Universal style in my QtQuick application, I am seeking to implement a ColorDialog for adjusting the accent color. My current setup looks like this: ColorDialog { id: accChooser title: "Please choose a color" onAcce ...

What is the best way to determine the remaining time until a cookie expires in seconds?

I recently set a cookie with an expiration time of 2 minutes. Now, I am looking for a way to display a countdown in HTML showing the seconds remaining before that specific cookie expires using Angular 2. ...

Implementing styles from a constant file in React Native: A simple guide

In my file register.js, I have a UI component. import CustomHeader from '../components/Header'; ... static navigationOptions = ({navigation, navigation: { state } }) => { return { title: '', headerSty ...

Issue with multiple sliders on the page not initializing pagination upon refreshing the page using Slick library

Every time I refresh the page, the pagination value fails to initialize until I click on either the next or previous button. var $slickElement = $('.paragraph-slider, .gallery-slider'); $slickElement.each(function() { if($(this).find('. ...

Utilize AngularJS to inject a value into the jk-rating-stars element

Hello there, I'm wondering how to assign a value to "rating" attribute as "ctrl.rating" using $scope in AngularJS. <jk-rating-stars max-rating="5" rating="ctrl.rating" read-only="ctrl.readOnly" on-rating="ctrl.onRating(rating)"> </jk-rat ...

Anticipating the execution of JavaScript code to finish

Below is the code snippet in question: var dataToSend2; // spawn new child process to call the python script const ls = spawn("python", ["./readDirectory.py"]); // collect data from script ls.stdout.on("data", function (info) { console.log("Pipe data ...

Error: Recaptcha does not have a constructor method

Out of nowhere, my application suddenly started throwing a TypeError: Recaptcha is not a constructor. recaptchaConfig() { this.recaptcha = new Recaptcha( config.service.recaptcha.client_key, config.service.recaptcha.sec ...

Is there a way to effortlessly append a slug to my URL in a Node.js platform?

Currently facing challenges with my templates. As I develop an e-commerce platform, I am using a json file containing product details to create cards for each product. Due to the large number of products, creating individual pages for each one is not feas ...

Tips for Extracting Data from JSON String in Automation Anywhere after Making a REST API Request

Can someone guide me on how to extract "item" details from the "searchResult" element in Automation Anywhere? I'm struggling with parsing a JSON string that was returned as part of a REST API call, and unlike UiPath, AA doesn't seem to provide an ...

Eliminate JSON entries that have identical values

Hey everyone, I've got a JSON file that looks like this. [ { "port": 8001, "password": "test123", "method": "aes-256-cfb" }, { "port": 8002, "password": "123test", "method": "aes-256-cfb" ...

Unusual "visual" phenomenon with autocomplete feature in VUE.js

Can someone review this code snippet? Check out the code here This is a peculiar example of a custom autocomplete VUE component. If you enter a value in one of the fields in Section 1 (like 'Apple'), then click on the Next button, you'll ...

Tips for integrating Material-UI's snackbar and input elements within a React application

I recently incorporated Material-UI components into my website design. One of the challenges I encountered was creating a functional interaction between the header component with a search field using mui's InputBase. My goal is to trigger a mui Snackb ...

Creating a custom if equals helper in Handlebars but encountering compilation errors

I have implemented a custom helper in Handlebars to create an if == "some string" type of helper. Here is the code for the helper: Handlebars.registerHelper('if_eq', function(a, b, opts) { if(a == b) // Or === depending on your needs ...

Leverage the object imported from the global <script> tag within a React component

I am currently attempting to incorporate a PayPal button into my React project. As per the instructions provided in PayPal's developer documentation, I have to include <script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID"& ...

Tips on choosing vml elements using jquery or vanilla javascript

I am trying to select a VML element using jQuery without relying on 'id' or 'class', but my attempts have been unsuccessful so far. <v:oval id="vmlElement" style='width:100pt;height:75pt' fillcolor="red"> </v:oval> ...

Method for displaying or concealing list items with an onClick event in React without relying on JQUERY

I'm working on a feature to show/hide a specific <li> element. While I know this can be achieved with JQuery, I prefer not to mix actual DOM manipulation with React's virtual DOM handling. With that in mind, I have assigned each <li> ...