display csv file inside a table using javascript - javascript

I have this script that gets the csv file, and separates it by column. I am having trouble to display the values in a table. I can't seem to get each column to create a new table row. Any help will be appreciated as I am not very good at JS.
<script>
getData();
async function getData() {
const response = await fetch('data.csv')
const data = await response.text();
console.log(data);
const table = data.split('\n');
table.forEach(row => {
const columns = row.split(',')
const date = columns[0]
const temp = columns[1]
console.log(date, temp);
})
}
</script>
The data.csv looks something like this:
17-10-2020,25
17-10-2020,25
17-10-2020,25
17-10-2020,25
17-10-2020,25
17-10-2020,25
17-10-2020,25
17-10-2020,25
The console.log(data, temp) returns without the commas. My only problem is trying to get them inside a table using Javascript.
<table class="table text-left mt-2" id="data">
<thead class="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col">Date/Time</th>
<th scope="col">Temperature</th>
</tr>
</thead>
<tbody>
<!-- Generate the csv table rows here -->
</tbody>
</table>

const tableBody = document.getElementById("table-body");
getData();
async function getData() {
const response = await fetch('data.csv')
const data = await response.text();
console.log(data);
const table = data.split('\n');
table.forEach((row,index) => {
const columns = row.split(',')
const date = columns[0]
const temp = columns[1]
console.log(date, temp);
const tr = document.createElement("tr");
tr.innerHTML = `
<td>${index + 1}</td>
<td>${date}</td>
<td>${temp}</td>
`;
// finally add the <tr> to the <tbody>
tableBody.append(tr);
})
}
<table class="table text-left mt-2" id="data">
<thead class="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col">Date/Time</th>
<th scope="col">Temperature</th>
</tr>
</thead>
<tbody id='table-body'>
<!-- Generate the csv table rows here -->
</tbody>
</table>
Try this and let me know if its working or not. Please note i've added an ID to the table body and selecting that via ID.

Related

API_Multiple users

**I need to make a table with 6 random users using html. I only get one user data !
what should i do ? do i have to make a loop ?
this is the code i useed **
i tried to change the id but there was no output.
please let me know what approach i shall follow.
`
<body>
<h2>API</h2>
<table>
<thead>
<th>Full Name</th>
<th>Age</th>
<th>Gender</th>
<th>Location</th>
<th>Country</th>
</thead>
<tbody>
<tr>
<td id="fullname"></td>
<td id="age"></td>
<td id="gender"></td>
<td id="location"></td>
<td id="counrty"></td>
</tr>
<tr>
<td id="fullname"></td>
<td id="age"></td>
<td id="gender"></td>
<td id="location"></td>
<td id="counrty"></td>
</tr>
</table>
<script>
const api_url="https://randomuser.me/api/";
async function getUser() {
const response= await fetch(api_url);
const data= await response.json();
const user=data.results[0];
let{first, last} = user.name;
let{gender, email, phone} = user;
let age = user.dob.age;
let{city, state, country} = user.location;
let fullName = first + " " + last;
document.querySelector("#fullname").textContent = fullName;
document.querySelector("#age").textContent = age;
document.querySelector("#gender").textContent = gender;
document.querySelector("#location").textContent = city + " ," + state;
document.querySelector("#counrty").textContent= country;
}
getUser();
</script>
</body>
</html>
`
what shall i do to take more random users ?
shall i create more ids?
I advise you when using any other people's code (api/framework etc.) to go and look at the documentation.
As you can see from my code below, you can specify how many users you want as return from the api and do a simple forEach to insert them into the table.
const userNumber = 6;
const api_url = "https://randomuser.me/api/?results=" + userNumber; //change number base to your need.
async function getUser() {
const response = await fetch(api_url);
const data = await response.json();
data.results.forEach(user => {
let {
first,
last
} = user.name;
let {
gender,
email,
phone
} = user;
let age = user.dob.age;
let {
city,
state,
country
} = user.location;
let fullName = first + " " + last;
document.querySelector('tbody').innerHTML +=
`<tr>
<td data-fullname>${fullName}</td>
<td data-age>${age}</td>
<td data-gender>${gender}</td>
<td data-location>${city} , ${state}</td>
<td data-country>${country}</td>
</tr>`;
});
}
getUser();
<h2>API</h2>
<table border="1">
<thead>
<th>Full Name</th>
<th>Age</th>
<th>Gender</th>
<th>Location</th>
<th>Country</th>
</thead>
<tbody></tbody>
</table>
Remember instead that the ID of the elements must be unique

How to search/find a words/data (in this case "Country ") from a table ( api data) with a search box?

I want to search country names with that text box, find the specific data from that massive list of names, and show that the only data to the user, not all the data. Please help me to do that. I have no idea how to do this.
// api section
const tbody = document.querySelector('#tbody');
const getdata = async () => {
const endpoint = "https://api.covid19api.com/summary",
response = await fetch(endpoint),
data = await response.json(),
Countries = data.Countries;
Countries.forEach(countryObj => {
let { Country, NewConfirmed, TotalConfirmed, NewDeaths, TotalDeaths, NewRecovered, TotalRecovered, Date } = countryObj;
tbody.innerHTML += `<tr>
<td>${Country}</td>
<td>${NewConfirmed}</td>
<td>${TotalConfirmed}</td>
<td>${NewDeaths}</td>
<td>${TotalDeaths}</td>
<td>${NewRecovered}</td>
<td>${TotalRecovered}</td>
<td>${Date}</td>
</tr>`;
});
}
getdata();
<---------------------------- search box function------------->
// Don't know how to do it.....help me ....Thanks in advance :)
<!--------------search Box & search button ------- -->
<input type="text" id="myInput" placeholder=" Search Country " >
<input type="submit" value="Search" class="submit">
<!----------------data table--------------- -->
<table class="table">
<thead>
<tr>
<th scope="col">Country</th>
<th scope="col">NewConfirmed</th>
<th scope="col">TotalConfirmed</th>
<th scope="col">NewDeaths</th>
<th scope="col">TotalDeaths</th>
<th scope="col">NewRecovered</th>
<th scope="col">TotalRecovered</th>
<th scope="col">Last Updated on</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
I want to search country names with that text box, find the specific data from that massive list of names, and show that the only data to the user, not all the data. Please help me to do that.
The only thing that is actually needed here is a way to 'search' the data and display those results. This can be done using the filter() method for an array.
Essentially, you just need to store your data in a global variable that can be filtered later, based on user input. Also, I usually make it a point to separate certain functionality, like displaying data. So instead of displaying the country data inside of the getData() function, I would create a separate function that just filters and displays data. This way you can call it after you fetch the data, and then call that same function each time you search (rather than have repeated code that displays countries in the table).
let countriesData = [];
const getdata = async () => {
const endpoint = "https://api.covid19api.com/summary",
response = await fetch(endpoint),
data = await response.json();
countriesData = data.Countries;
_DisplayCountries();
}
const _DisplayCountries = (c = "") => {
let tbody = document.querySelector("#tbody");
tbody.innerHTML = ``;
countriesData.filter(country => country.Country.toLowerCase().includes(c.toLowerCase())).forEach(result => {
tbody.innerHTML += `<tr>
<td>${result.Country}</td>
<td>${result.NewConfirmed}</td>
<td>${result.TotalConfirmed}</td>
<td>${result.NewDeaths}</td>
<td>${result.TotalDeaths}</td>
<td>${result.NewRecovered}</td>
<td>${result.TotalRecovered}</td>
<td>${result.Date}</td>
</tr>`;
});
}
getdata();
document.querySelector("#mySubmit").addEventListener("click", e => {
_DisplayCountries(document.querySelector("#myInput").value);
});
<input type="text" id="myInput" placeholder=" Search Country ">
<input type="submit" id="mySubmit" value="Search" class="submit">
<table class="table">
<thead>
<tr>
<th scope="col">Country</th>
<th scope="col">NewConfirmed</th>
<th scope="col">TotalConfirmed</th>
<th scope="col">NewDeaths</th>
<th scope="col">TotalDeaths</th>
<th scope="col">NewRecovered</th>
<th scope="col">TotalRecovered</th>
<th scope="col">Last Updated on</th>
</tr>
</thead>
<tbody id="tbody"></tbody>
</table>
NOTES
There are definitely a lot of different ways to filter() the data and I opted for a very simple includes() method. I also added toLowerCase() to the country and the search string to make it case-insensitive, but I understand there are several ways to do this as well.
let regex = new RegExp(c, "i");
countriesData.filter(country => country.Country.match(regex))
That for example would also return a list of search results that are case-insensitive.

How to retrieve an array from Firestore and output it onto an HTML table [duplicate]

I am designing a web page that will obtain data from my firestore collection and display each document with its corresponding fields Here is the code:
<table class="table is-striped is-narrow is-hoverable is-fullwidth">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>AR Level</th>
</tr>
</thead>
<tbody id="myTable">
</tbody>
</table>
here is the JS:
db.collection("books").where("ItemType", "==", "Book").where("Program", "==", "AR")
.get()
.then(
function(querySnapshot){
querySnapshot.forEach(function(doc){
dataObj = doc.data()
console.log(dataObj)
buildTable(dataObj)
function buildTable(data){
var table = document.getElementById('myTable')
for (var i = 0; i < data.length; i++){
var row = `<tr>
<td>${data[i].Title}</td>
<td>${data[i].Author}</td>
<td>${data[i].Points}</td>
</tr>`
table.innerHTML += row
}
}
})
}
)
I don't see why you're using a for loop in your function. Unless one "Book" document is an Array of items each having the Title/Author/Points fields.
You're basically looping through the data object as if it's an array. Chances are, it's not.
If I'm right, and one "Book" document is object/map containing those three fields, then your code should be like this:
db.collection("books").where("ItemType", "==", "Book").where("Program", "==", "AR")
.get()
.then(querySnapshot=>{
querySnapshot.forEach(doc=>{
let data = doc.data();
let row = `<tr>
<td>${data.Title}</td>
<td>${data.Author}</td>
<td>${data.Points}</td>
</tr>`;
let table = document.getElementById('myTable')
table.innerHTML += row
})
})
.catch(err=>{
console.log(`Error: ${err}`)
});

How can I display all data from Firestore documents into an html table

I am designing a web page that will obtain data from my firestore collection and display each document with its corresponding fields Here is the code:
<table class="table is-striped is-narrow is-hoverable is-fullwidth">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>AR Level</th>
</tr>
</thead>
<tbody id="myTable">
</tbody>
</table>
here is the JS:
db.collection("books").where("ItemType", "==", "Book").where("Program", "==", "AR")
.get()
.then(
function(querySnapshot){
querySnapshot.forEach(function(doc){
dataObj = doc.data()
console.log(dataObj)
buildTable(dataObj)
function buildTable(data){
var table = document.getElementById('myTable')
for (var i = 0; i < data.length; i++){
var row = `<tr>
<td>${data[i].Title}</td>
<td>${data[i].Author}</td>
<td>${data[i].Points}</td>
</tr>`
table.innerHTML += row
}
}
})
}
)
I don't see why you're using a for loop in your function. Unless one "Book" document is an Array of items each having the Title/Author/Points fields.
You're basically looping through the data object as if it's an array. Chances are, it's not.
If I'm right, and one "Book" document is object/map containing those three fields, then your code should be like this:
db.collection("books").where("ItemType", "==", "Book").where("Program", "==", "AR")
.get()
.then(querySnapshot=>{
querySnapshot.forEach(doc=>{
let data = doc.data();
let row = `<tr>
<td>${data.Title}</td>
<td>${data.Author}</td>
<td>${data.Points}</td>
</tr>`;
let table = document.getElementById('myTable')
table.innerHTML += row
})
})
.catch(err=>{
console.log(`Error: ${err}`)
});

How i can clear/refresh my table before getting new data from api?

I am trying to retrieve datas from an api by triggering a button.but evertimes i click the button the old datas remain exist which i dont want.i want the table will be reloaded and will have new datas from api.
const showData = document.querySelector('.showData')
const btn = document.querySelector('.shwData-btn')
btn.addEventListener('click', showdata)
function showdata(){
fetch('http://localhost:5000/posts')
.then(res => res.json())
.then(data=>{
data.forEach(item =>{
const id = item['_id']
const name = item.name
const email = item.email
const age = item.age
const tr = document.createElement('tr')
tr.innerHTML = `
<tr>
<td>${id}</td>
<td>${name}</td>
<td>${email}</td>
<td>${age}</td>
</tr>
`
showData.appendChild(tr)
})})}
<!-- language: lang-html -->
<button class="shwData-btn">Showdata</button>
<table class="showData">
<tr>
<td>id</td>
<td>email</td>
<td>name</td>
<td>age</td>
</tr>
</table>
You will have to render a blank table or clear all rows(tr) before populating it with data.
const showData = document.querySelector('.showData')
const btn = document.querySelector('.shwData-btn')
btn.addEventListener('click', showdata)
function showdata(){
fetch('http://localhost:5000/posts')
.then(res => res.json())
.then(data=>{
// Clear your table here or populate with blank data
// tbody because you do not want to clear column heading. Make sure you have tbody and theader
$(".showData tbody tr").remove();
data.forEach(item =>{
const id = item['_id']
const name = item.name
const email = item.email
const age = item.age
const tr = document.createElement('tr')
tr.innerHTML = `
<tr>
<td>${id}</td>
<td>${name}</td>
<td>${email}</td>
<td>${age}</td>
</tr>
`
showData.appendChild(tr)
})})}
<!-- language: lang-html -->
<button class="shwData-btn">Showdata</button>
<table class="showData">
<tr>
<td>id</td>
<td>email</td>
<td>name</td>
<td>age</td>
</tr>
</table>
Highly recommend to have a look at this as well:
Delete all rows in an HTML table

Categories