fetch json to table (endpoint) - javascript

i'm beginner on javascript trying to learn everyday, here i'm trying to fetch json data from url with endpoints, for some reason data is not coming to 'table' i can see it in console.log but not on table.
my json data looks like this :
{
"id": "145127236",
"mygoals": "success",
"future": "high",
"dole": {
"Key": "fhd699f"
}
}
and my code like this :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<style>
</style>
</head>
<body>
<div class="container">
<table class="table table-stripped">
<thead>
<tr>
<th> emp id</th>
<th> emp mygoals</th>
<th> emp future</th>
</tr>
</thead>
<tbody id="data" >
</tbody>
</table
</div>
<script>
fetch("https://sp*****.com/get/henkilot/98765432/sijoitus",
{
method: "GET",
headers: {
"x-api-key": "p*****w"
}
}
).then(res =>{
res.json().then(
data=> {
console.log(data);
if(data.length > 0){
var temp ="";
data.forEach((u) =>{
temp +="<tr>";
temp += "<td>"+u.id+"</td>";
temp += "<td>"+u.mygoals+"</td>";
temp += "<td>"+u.future+"</td></tr>";
})
document.getElementById("data").innerHTML = temp
}
}
)
}
)
.catch(err => {
console.log("ERROR: " + err);
});
</script>
</body>
</html>

It seems the JSON data that you wrote in the question is not an array, therefore there is no need to iterate over the data. One option is to remove the forEach or fix the endpoint response if you have access to it.
This is the code that considers that the endpoint does not respond with an array:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<style>
</style>
</head>
<body>
<div class="container">
<table class="table table-stripped">
<thead>
<tr>
<th> emp id</th>
<th> emp mygoals</th>
<th> emp future</th>
</tr>
</thead>
<tbody id="data" >
</tbody>
</table>
</div>
<script>
fetch("https://asdasd.free.beeceptor.com/a",
{
method: "GET",
headers: {
"x-api-key": "p*****w"
}
}
).then(res =>{
res.json().then(
data=> {
console.log(data);
var temp ="";
temp +="<tr>";
temp += "<td>"+data.id+"</td>";
temp += "<td>"+data.mygoals+"</td>";
temp += "<td>"+data.future+"</td></tr>";
document.getElementById("data").innerHTML = temp
}
)
}
)
.catch(err => {
console.log("ERROR: " + err);
});
</script>
</body>
</html>

Your braces are insane
try that:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<table class="table table-stripped">
<thead>
<tr>
<th> emp id </th>
<th> emp mygoals </th>
<th> emp future </th>
</tr>
</thead>
<tbody id="data"></tbody>
</table>
</div>
<script>
const tableData = document.getElementById("data")
;
fetch("https://sp*****.com/get/henkilot/98765432/sijoitus",
{ method: "GET"
, headers: { "x-api-key": "p*****w" }
})
.then(res=>res.json())
.then(data=>
{
console.log(data)
data.forEach(u=>
{
let newRow = tableData.insertRow()
newRow.insertCell().textContent = u.id
newRow.insertCell().textContent = u.mygoals
newRow.insertCell().textContent = u.future
})
})
.catch(err => console.log("ERROR: " + err) );
</script>
</body>
</html>

Related

Why is my insertRow method adding blank cells to my table?

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..
total() is probably called before the number is populated. You should have it execute after the cell is populated and not on click.

Get data from a table html with click

Good afternoon, I'm a beginner, I'm having trouble getting information from a table that consumes data from an api.
index.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">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="main.js"></script>
<title>Document</title>
</head>
<body onload="apendeOnClick()">
<table id="tablerow">
<caption>Alien football stars</caption>
<thead>
<tr>
<th>DATA</th>
<th>TELEFONE</th>
<th>RAMAL</th>
<th>DESCRIÇÃO</th>
<th>ACÕES</th>
</tr>
</thead>
<tbody id="table_body">
</tbody>
</table>
<script>
</script>
</body>
</html>
My code is this, it feeds the table normally, but I would like when the person clicks on the row button to display the information in the alert.
main.js
fetch("https://my-json-server.typicode.com/lfnoleto/api-fake/contact").then((data) => {
return data.json()
}).then((Objectdata) => {
//console.log(Objectdata[0].data)
let tabelaData = ""
Objectdata.map((values)=>{
tabelaData += `<tr>
<td>${values.data}</td>
<td>${values.tefone}</td>
<td>${values.ramal}</td>
<td>${values.descricao}</td>
<td><button id="butao" class="btn btn-success" ><i class="fa fa-phone"></button></td>
</tr>`
})
document.getElementById("table_body").innerHTML = tabelaData
innerHTML = tabelaData
})
function apendeOnClick(){
const table = document.getElementById("tablerow")
console.log(table)
if (table) {
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].childNodes[5].childNodes[1].onclick = function() {
tableText(this);
};
}
}
}
function tableText(tableRow) {
let telefone = tableRow.childNodes[1].innerHTML;
let ramal = tableRow.childNodes[2].innerHTML;
let obj = {'telefone': telefone, 'ramal': ramal};
console.log(obj);
}
I hope that when the person clicks on the telephone icon, he displays the extension and telephone information
you can use data attribute to store extension info or other information.
<button id="butao" data-extension="123" class="btn btn-success" >
in javascript :
const button = document.querySelector('button');
button.dataset.extention // "123"
a good references:
https://www.w3schools.com/tags/att_data-.asp
https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

jQuery $.each iterating through firebase array twice

I am trying to use jQuery with firebase on the web and am building a quick table of users and tickets. The users and tickets are displaying properly, however they are iterated over twice, in that the table contains the same users and tickets twice. I am not sure what is happening.`
var users = ["Nick","Peter"];
var rows = "";
var number = 0;
//Sync all changes
dbRefAllUsers.on('value', function(snap) {
console.log("#Run",number+1);
jQuery.each(users, function(index,name){
console.log(name);
rows += "<tr><td>" + name + "</td><td>" + snap.child(name).child("tickets").val() + "</td></tr>";
console.log(rows);
});
$(rows).appendTo("#ticketTable tbody");
return head.innerText = JSON.stringify(snap.val(), null, 3);
});`
HTML:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title></title>
</head>
<body>
<h1 id="head"></h1>
<script src="https://www.gstatic.com/firebasejs/3.6.7/firebase.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="./app.js"></script>
<table id="ticketTable" style="font-size:18px;">
<thread>
<tr>
<th>Users</th>
<th>Tickets</th>
</tr>
</thread>
<tbody>
</tbody>
</table>
</body>
</html>

Fetching api data in angular

I am creating an application related to cricket match information in angular. Am getting problem in fetching api response. you can check api response here.
Console is showing error, please check
Here is my code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container" ng-app="cricApp" ng-controller="cricCtrl">
<div class="form-group">
<h2>Your result</h2>
<table class="table table-striped">
<thead>
<tr><th colspan="4"><h4>Cricket Match Info</h4></th></tr>
<tr>
<th>Sno</th>
<th>unique_id</th>
<th>description</th>
<th>title</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="match in matchList | filter: nameFilter">
<td>{{$index + 1}}</td>
<td>
{{match.unique_id}}
</td>
<td>{{match.description}}</td>
<td>{{match.title}}</td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script>
angular.module('cricApp', []).
controller('cricCtrl', function($scope, $http) {
$scope.matchList = [];
$http.get("http://cricapi.com/api/cricket").then(function (response) {
console.log(response);
$scope.matchList = response.data;
});
}
);
</script>
</body>
</html>
your code is fine just replace
$scope.matchList = response.data;
with
$scope.matchList = response.data.data;
because actual data is coming in data inside response.data.

Cannot display result in browser using IMBD api

Data shows in console but cannot display in browser. I almost tried in all browser but same result. row's are creating according to search result but nothing appears inside rows, all rows are blank. Any help will be appreciable.
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>IMDB</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script src="imdb.js"></script>
</head>
<body>
<div class="container">
<h1>Search IMDB</h1>
<input type="text" id="movieTitle" class="form-control" placeholder="Ex: Titanic"/>
<button id="searchMovie" class="btn btn-primary btn-block">Search Movie</button>
<table class="table table-striped" id="results">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th>Rating</th>
<th>Image</th>
</tr>
</thead>
<tbody id="container">
<tr id="template">
<td></td>
<td class="plot"></td>
<td class="rating"></td>
<td><img src="" class="poster"/></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
imdb.js
(function(){
$(init);
function init(){
$("#searchMovie").click(searchMovie);
var movieTitle = $("#movieTitle");
var tbody = $("#container");
var template = $("#template").clone();
function searchMovie(){
var title = movieTitle.val();
$.ajax({
url: "http://api.myapifilms.com/imdb/idIMDB?title="+title+"&limit=3&token=1ec543f9-d889-4865-8aab-62a2515f24e8",
dataType: "jsonp",
success: renderMoviesWithTemplate
}
);
function renderMoviesWithTemplate(movies){
console.log(movies);
tbody.empty();
for(var m in movies){
var movie = movies[m];
var title = movie.title;
var plot = movie.plot;
var rating = movie.rating;
var posterUrl = movie.urlPoster;
var movieUrl = movie.urlIMDB;
var tr = template.clone();
tr.find(".link")
.attr("href",movieUrl)
.html(title);
tr.find(".plot")
.html(plot);
tr.find(".rating")
.html(rating);
tr.find(".poster")
.attr("src",posterUrl);
tbody.append(tr);
}
}
}
}
})();

Categories

Resources