Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load Async Data in Jquery Datatable

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"}
]
like image 742
mcfred Avatar asked Oct 20 '25 21:10

mcfred


1 Answers

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/

like image 168
shubham Avatar answered Oct 22 '25 18:10

shubham