I am trying to load data from a remote URL like below:
const getPeople = async () => {
const data = await fetch('https://randomurl', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
});
const jsondata = await data.json();
console.log(jsondata);
return jsondata;
}
Here's my datatable:
$(document).ready(function () {
var table = $("#records").DataTable({
data: getPeople(),
columns: [
{
data: "NAME",
},
{
data: "SCHOOL",
},
{
data: "CLASS"
},
{
data: "CITY"
}
]
});
});
I am not getting any error when I load the page. However, my datatable is empty. I have verified that the getPeople() function does return json data. Am I missing anything?
The console.log(jsondata) displays the data 2 or 3 seconds after the datatable is created. So how can I display/create the datatable after getting the data?
Here's the returned json:
[
{"NAME":"joe","SCHOOL":"Rogers","CLASS":8,"CITY":"Sisily"},
{"NAME":"sam","SCHOOL":"Matt","CLASS":6,"CITY":"Monaco"}
]
Calling the function to initialise the datatable after you've got the JSON response should work.
$(document).ready(function () {
var asyncData;
getdata();
function getdata(){
const getPeople = async () => {
const data = await fetch('https://api.myjson.com/bins/y53hs', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
});
const jsondata = await data.json();
asyncData=jsondata.data;
initialiseTable();
return jsondata;
};
getPeople();
}
function initialiseTable(){
var table = $("#records").DataTable({
data: asyncData,
columns: [
{
data: "NAME",
},
{
data: "SCHOOL",
},
{
data: "CLASS"
},
{
data: "CITY"
}
]
});
}
});
working fiddle at https://jsfiddle.net/ourqh9ts/2/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With