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>