Retrieving JSON data to create and showcase an HTML table

Can you help me figure out what's going wrong with my code?

I have an HTML page with a table where I fetch data from the web in JSON format using JavaScript. The logic works perfectly when the fetch code is let to run on its own, but when I try to execute it from a function called by an onclick event on a submit button, it stops working. I've tried different approaches like regular functions and async/await, but nothing seems to work.

Below is a snippet of my code starting at the form:

Thank you for your help!


<form enctype="multipart/form-data" action="" method="post">
    <button type="submit" name="submit" id="Submit" value="click" onClick = getEarnings()>Click </button>
</form>

<table>
  <thead>
    <tr">
        <th>Reported Date</th>
        <th>Reported EPS</th>
        <th>Estimated EPS</th>
        <th>Surprise</th>
    </tr>
  </thead>
  <tbody id="myData"><tbody>
</table>

<script>
/* function getEarnings() { */
    fetch('https://www.alphavantage.co/query?function=EARNINGS&symbol=IBM&apikey=demo')
      .then(res => res.text())
      .then((out) =>
         {
            alert("I am here"); // I can't see it if from function
            let jsonData = JSON.parse(out);
            for (let i = 0; i < jsonData.quarterlyEarnings.length; i++)
             {
                let earnings = jsonData.quarterlyEarnings[i];
                document.getElementById("myData").innerHTML +=
                "<tr><td>" + earnings.reportedDate + "</td>" +
                "<td align='right'>" + earnings.reportedEPS + "</td>" +
                "<td align='right'>" + earnings.estimatedEPS + "</td>" +
                "<td align='right'>" + earnings.surprise + "</td></tr>";
             };
         })
      .catch(err => console.error(err));
/* } */
</script>

Answer №1

You can easily retrieve data without the need for a form. Here's my recommendation:

getData.onclick = () => {
  fetch('https://www.alphavantage.co/query?function=EARNINGS&symbol=IBM&apikey=demo')
    .then(res => res.text())
    .then((out) => {
      let jsonData = JSON.parse(out);
      for (let i = 0; i < jsonData.quarterlyEarnings.length; i++) {
        let earnings = jsonData.quarterlyEarnings[i];
        myData.innerHTML +=
          "<tr><td>" + earnings.reportedDate + "</td>" +
          "<td align='right'>" + earnings.reportedEPS + "</td>" +
          "<td align='right'>" + earnings.estimatedEPS + "</td>" +
          "<td align='right'>" + earnings.surprise + "</td></tr>";
      };
    })
    .catch(err => console.error(err));
}
<button type="button" id="getData">Retrieve Data</button>
<table>
  <thead>
    <tr>
      <th>Reported Date</th>
      <th>Reported EPS</th>
      <th>Estimated EPS</th>
      <th>Surprise</th>
    </tr>
  </thead>
  <tbody id="myData">
    <tbody>
</table>

Answer №2

When the button in the <Tag> element is clicked, it triggers a page refresh which should be avoided.

function retrieveEarnings(e) {
    // Prevent the browser from refreshing
    e.preventDefault();

    // Call fetch function here
}

Answer №3

Here are a few key points to consider:

  1. It's recommended to use "onclick" instead of "onClick" for consistency.
  2. When setting the call on your HTML attribute, make sure to enclose it in quotes like this:
    onClick="getEarnings();"
  3. To prevent a page reload with a submit type button, you can either change the button type to "button" or handle the event and stop it from continuing within your function as shown below:
function getEarnings (e) {
    // Prevent page reload caused by submit button
    e.preventDefault();
    // Add your logic here
}

Ideally, consider moving this logic to a separate script file where you can target your button using a unique id and set an event listener once the DOM has loaded. This separation of presentation and logic is good practice. Here's a basic example:

window.addEventListener('DOMContentLoaded', function () {
    const submitButton = document.getElementById('Submit');
    submitButton.addEventListener('click', function (e) {
       e.preventDefault();
       // Implement your logic here
    });
});

Additional Notes:

  • Lowercase usage in JavaScript, such as using "onclick," is generally preferred over mixed case for consistency.
  • For legacy browser support, be mindful of differences between click events handled with addEventListener compared to traditional onclick methods.

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

Spin and flip user-submitted images with the power of HTML5 canvas!

I am currently working on a profile upload system where we are implementing image rotation using the HTML5 canvas object with JavaScript. Although the uploaded image is rotating, we are facing issues where parts of the image are being cut off randomly. So ...

Easily changing the state of a specific array item using React

I'm having trouble updating the state of a specific item in an array called reviews. Can someone guide me on how to achieve this? The following code snippet is not working as expected: this.setState({ reviews[2].current: true }); Below is the comp ...

What sets my project apart from the rest that makes TypeScript definition files unnecessary?

Utilizing .js libraries in my .ts project works seamlessly, with no issues arising. I have not utilized any *.d.ts files in my project at all. Could someone please explain how this functionality is achievable? ...

Rules for validating string and numeric combinations in Vuetify are essential for ensuring accurate

Looking for guidance on implementing Vuetify validation to enforce rules (using :rules tag on a v-text-field) in the format of AB-12345678 (starting with two letters followed by a hyphen and then an 8-digit number). I'm having difficulty achieving thi ...

The NPM command fails to execute the Webpack script, yet it successfully runs when manually entered into the terminal

Working on my project with Electron-React-Boilerplate, I encountered an issue while running npm run build-renderer. Despite the script appearing to finish, I receive an error. If I manually enter the code related to the build-renderer script in the termin ...

Trouble with Callback firing in Select2's 'Infinite Scroll with Remote Data' feature

After reviewing the tutorial on the Select2 project page, I am implementing a feature to load additional records as the user scrolls to the end of the results. <script> $(document).ready(function() { $('#style_full_name').select2({ ...

How can we redirect to another page after checking a box?

In the scenario where a checkbox is checked, how can the page be automatically redirected to @habit, simulating the behavior of clicking a submit button? habits/show <% if @habit.current_level_strike %> <div class="btn" id="red"> <l ...

What is the best way to send an Ajax Json Response to a php script?

My current setup involves an Ajax call using the xmlHttpRequest to retrieve data from a server. I aim to format this response into a specific string and share it on a different server. To achieve my goal, I am leveraging a php script for processing the fo ...

display the text from the template after selecting it (including both the text-field and value-field)

I'm currently utilizing BootstrapVue. In my b-form-select component, I display the name (as the text field) in the selection within my child.vue and emit the age (as the value field) to my parent.vue. This functionality is functioning as intended. H ...

Discover an Element within a JSON Array and Append a New Value to it

I've got an array of JSON data structured like this: [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Eve' } ] My goal is to locate an object by its id and append a ...

What is the best way to conditionally render table data in React JS using a loop?

Currently, I'm working on a project with React.js and facing challenges in iterating through a data array to selectively render elements based on each data node's properties. The dataset is structured as follows: var requests = [ {"id": ...

Is there a way to retrieve files from a main directory as well as all its subdirectories?

I'm looking to find a way to retrieve all JavaScript files located in the main directory and any subdirectories for my discord.js command handler. How can I make this happen? I have a functioning code snippet that successfully retrieves all .js files ...

Minecraft-Forge: Tracking JSON file checksums

I am currently developing a custom launcher for Minecraft that incorporates Forge. The issue I'm currently grappling with pertains to hashes. Vanilla Minecraft's hashes are SHA1 Hashes, which is standard (example here: ). However, when it comes t ...

Using AngularJS to refresh information stored in an array

My objective is to create a basic application that allows users to adjust their availability on weekdays. The code is functioning correctly as it retrieves data from the select box. However, I encounter an issue when trying to update Monday's data and ...

Different options for determining network connectivity on a website

Seeking Network and Location Information on ASP.Net Core MVC Web Application After some investigation, I came across the Navigator API online. For acquiring location data, it functions flawlessly. navigator.geolocation.getCurrentPosition(function (posi ...

Each loop in the forEach function triggers the mouseup event

I am currently utilizing a foreach loop: objects.forEach(function(object) { var button = '<tr><td>' + object.object.code + '</td><td>' + formatDistance(1456000) + &apos ...

Node JS confirmation dialog box

I need to incorporate a confirmation message in my application that will execute the action if the user clicks submit, but cancel the event if they don't. I have set up a route in Express for this purpose, however I want to prevent the backend code f ...

Having trouble parsing an array from Alamofire in iOS using SwiftyJSON? You may encounter null values while attempting to parse

Here is the response from the API request: [ { " ..... I am currently using SwiftyJSON to parse the data received from an Alamofire request: let json = JSON(data) let mapHeir = json[0]["Info"]["String"] print(mapHeir) However, I am facing ...

Utilizing jQuery's Chained Selectors: Implementing Selectors on Previously Filtered Elements

DO NOT MISS: http://jsfiddle.net/gulcoza/9cVFT/1/ LATEST FIDDLE: http://jsfiddle.net/gulcoza/9cVFT/4/ All the code can be found in the above fiddle, but I will also explain it here: HTML <ul> <li id="e1">1</li> <li id="e2" ...

I would like to hide the button if there are fewer than five visible

When there are less than 5 visible buttons, I want the button to be invisible. The state visible outputs 5 buttons each time. On the detail page, I would like to have the buttons invisible if there are fewer than 5 outputs. In my current code, when ther ...