I am trying to add the results from a fetch request into a new row in a table. However, When I run the function to do that, the first click adds a blank row instead of adding my desired data. Additionally, the data that I would have liked to add gets added the next time the function is ran. I have no idea what is wrong and I have tried so many things. I believe this problem is causing my other function called "total()" to return an error as the first cell is undefined instead of containing a value.
Here is my javascript:
document.getElementById('getFood').addEventListener('click', getFood);
document.getElementById('getFood').addEventListener('click', total);
/*function getText() {
$.ajax({
method: 'GET',
url:
'https://api.api-ninjas.com/v1/nutrition?query=' +
document.getElementById('foodInput'),
headers: { 'X-Api-Key': 'vrtwcc/pVgAr2o/a4dEyYA==hR1m7lLVdU4ho4hW' },
contentType: 'application/json',
success: function (result) {
console.log(result);
},
error: function ajaxError(jqXHR) {
console.error('Error: ', jqXHR.responseText);
},
});
}*/
/*function getFood(foodName) {
let xhr = new XMLHttpRequest();
xhr.open(
'get',
'https://api.api-ninjas.com/v1/nutrition?query=' + foodName,
true
);
xhr.send();
xhr.addEventListener('load', function () {
console.log(xhr.responseText);
});
}
getFood('fries');*/
function getFood() {
fetch(
'https://api.api-ninjas.com/v1/nutrition?query=' +
`${document.getElementById('foodInput').value}`,
{
method: 'GET',
headers: { 'X-Api-Key': 'vrtwcc/pVgAr2o/a4dEyYA==hR1m7lLVdU4ho4hW' },
contentType: 'application/json',
}
)
.then((res) => res.json())
.then((data) => {
foodQuery = data[0].name;
calorieQuery = `${data[0].calories} calories`;
});
let table = document
.getElementById('foodTable')
.getElementsByTagName('tbody')[0];
let row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = foodQuery;
cell2.innerHTML = calorieQuery;
// row.insertCell(0).innerHTML = foodQuery;
// row.insertCell(1).innerHTML = calorieQuery;
//document.getElementById('foodInput').value = '';
}
function total() {
let table = document.getElementById('foodTable');
let total = 0;
for (let i = 1; i < table.rows.length; i++) {
total += Number(table.rows[i].cells[2].innerText);
}
document.getElementById('tableTotal').value = total;
}
and here is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script
src="https://code.jquery.com/jquery-3.6.3.js"
integrity="sha256-nQLuAZGRRcILA+6dMBOvcRh5Pe310sBpanc6+QBmyVM="
crossorigin="anonymous"
></script>
<link
rel="stylesheet"
href="node_modules/bootstrap/dist/css/bootstrap.css"
/>
<link rel="stylesheet" href="style.css" />
<title>Document</title>
</head>
<body>
<div class="container-fluid border border-primary">
<strong>Jason's Calorie Counter </strong><br />
<form>
<div class="form-group" id="">
<label>Food Selection</label>
<input
class="form-control"
id="foodInput"
placeholder="Enter food here"
/>
<small id="foodHelp" class="form-text text-muted"
>Nutrition data for each food item is scaled to 100g unless a
quantity is specified
</small>
<br />
<button type="button" class="btn btn-primary" id="getFood">
Get Food
</button>
</div>
</form>
</div>
<table class="table table-bordered" id="foodTable">
<thead>
<tr>
<th scope="col">Food</th>
<th scope="col">Calories</th>
</tr>
</thead>
<tbody>
<tr id="rows1">
<td colspan="2" id="tableTotal">Total</td>
</tr>
</tbody>
</table>
<script
src="https://cdn.jsdelivr.net/npm/popper.js@1.14.7/dist/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"
></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"
></script>
<script src="script.js"></script>
</body>
</html>
One more important detail: The new row gets added correctly when just adding a string, so it may have to do with the variable or the fetch request. Thank you very much for your time and if there is more information that is missing, please tell me and I will do my best to add it.
I have tried changing the type of data being added, adding them to different parts of the table, changing syntax, etc..
Via Active questions tagged javascript - Stack Overflow https://ift.tt/MSBcpkj
Comments
Post a Comment