I need to retrieve data from a server and display it in an HTML table. The server contains an array of weather forecast information as shown below.
[{"date":"19\/08\/2020","weather":"Sunny","temperature":30,"temp_unit":"celcius"},
{"date":"30\/08\/2020","weather":"Sunny","temperature":31,"temp_unit":"celcius"},
{"date":"21\/08\/2020","weather":"Cloudy","temperature":29,"temp_unit":"celcius"},
{"date":"22\/08\/2020","weather":"Sunny","temperature":29,"temp_unit":"celcius"},
{"date":"23\/08\/2020","weather":"Sunny","temperature":31,"temp_unit":"celcius"},
{"date":"24\/08\/2020","weather":"Sunny","temperature":30,"temp_unit":"celcius"},
{"date":"25\/08\/2020","weather":"Cloudy","temperature":28,"temp_unit":"celcius"},
{"date":"26\/08\/2020","weather":"Cloudy","temperature":27,"temp_unit":"celcius"},
{"date":"27\/08\/2020","weather":"Sunny","temperature":29,"temp_unit":"celcius"},
{"date":"28\/08\/2020","weather":"Sunny","temperature":28,"temp_unit":"celcius"},
{"date":"29\/08\/2020","weather":"Cloudy","temperature":28,"temp_unit":"celcius"},
{"date":"30\/08\/2020","weather":"Sunny","temperature":31,"temp_unit":"celcius"}]
I've created the following code to retrieve the data using an AJAX call, but when I try to display it in a table, all values show as undefined.
//include CSS in this file
import './style.css';
//jQuery already imported
import $ from 'jquery';
// AJAX call to load data
var myArray = []
$.ajax({
method: 'GET',
url: 'https://www.seetrustudio.com/data.php',
success: function(response) {
myArray = response
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].date}</td>
<td>${data[i].weather}</td>
<td>${data[i].temperature}</td>
<td>${data[i].temp_unit}</td>
</tr>`
table.innerHTML += row
}
}
How can I resolve this issue and correctly populate the HTML table with the list?