I want to get the time data and the temperature data (for all 7 days) from JSON (that came after my initial request to an external weather API - open meteo), parse the JSON and populate a HTML table with it. I cant get to populate the table with data....below is my code, please help me!
Thank you!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style>
th{
color:#fff;
}
</style>
<table >
<tr >
<th>time</th>
<th>temperature</th>
</tr>
<tbody id="myTable">
</tbody>
</table>
<script>
var myArray = [
]
$.ajax({
method: 'GET',
url: 'https://api.open-meteo.com/v1/forecast?latitude=44.32&longitude=23.80&start_date=2022-11-30&end_date=2022-12-06&daily=temperature_2m_max&timezone=GMT',
success:function(response){
myArray = response.daily
buildTable(myArray)
console.log(myArray)
}
})
function buildTable(data){
var table = document.getElementById('myTable')
for (var i = 0; i < data.length; i ){
var row = `<tr>
<td>${data[i].time}</td>
<td>${data[i].temperature_2m_max}</td>
</tr>`
table.innerHTML = row
}
}
</script>
The JSON data that I get
Raw--
{"latitude":44.3125,"longitude":23.8125,"generationtime_ms":0.3180503845214844,"utc_offset_seconds":0,"timezone":"GMT","timezone_abbreviation":"GMT","elevation":106.0,"daily_units":{"time":"iso8601","temperature_2m_max":"°C"},"daily":{"time":["2022-11-30","2022-12-01","2022-12-02","2022-12-03","2022-12-04","2022-12-05","2022-12-06"],"temperature_2m_max":[5.9,6.1,8.1,9.5,9.3,7.3,4.3]}}
Parsed ---
{
"latitude": 44.3125,
"longitude": 23.8125,
"generationtime_ms": 0.3180503845214844,
"utc_offset_seconds": 0,
"timezone": "GMT",
"timezone_abbreviation": "GMT",
"elevation": 106,
"daily_units": {},
"daily": {
"time": [
"2022-11-30",
"2022-12-01",
"2022-12-02",
"2022-12-03",
"2022-12-04",
"2022-12-05",
"2022-12-06"
],
"temperature_2m_max": [
5.9,
6.1,
8.1,
9.5,
9.3,
7.3,
4.3
]
}
}
CodePudding user response:
Try this
function buildTable(data){
var table = document.getElementById('myTable')
for (var i = 0; i < data.time.length; i ){ // edited
var row = `<tr>
<td>${data.time[i]}</td> // edited
<td>${data.temperature_2m_max[i]}</td> // edited
</tr>`
table.innerHTML = row
}
}
CodePudding user response:
It works, Thank you!
function buildTable(data){
var table = document.getElementById('myTable')
for (var i = 0; i < data.time.length; i ){ // edited
var row = `<tr>
<td>${data.time[i]}</td> // edited
<td>${data.temperature_2m_max[i]}</td> // edited
</tr>`
table.innerHTML = row
}
}