Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my JQuery DataTable not populating from an array?

I’m trying to create a datatable of golf players from an API call, but my table just says "No data available in table". I have debugged through and can see that the data array contains the correct information and format, and looking at the datatables documentation, I’m not sure what I’m doing wrong.

Javascript:

let data;
            $.ajax({
                url: "https://pure-peak-65624.herokuapp.com/https://api.sportradar.us/golf/trial/v3/en/players/wgr/2022/rankings.json?api_key=rupvugmcybede53f3svuqqa8",
                dataType: 'json',
                success: function (json) {
                    console.log("success");
                    data = json.players;
                },
                error: function (e) {
                    console.log("error");
                }
            });

            $('#myTable').DataTable({
                data: data,
                columns:[
                    {data: 'id'},
                    {data: 'first_name'}
                ]
            });

        });

Picture of empty DataTable

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

At first I tried to load the data into the table using ajax in the datatable function, but when that didn’t work I broke it up into a separate ajax call to try and debug easier.

>Solution :

You should probably fill you dataTable inside your ajax success

let data;
$.ajax({
  url: "https://pure-peak-65624.herokuapp.com/https://api.sportradar.us/golf/trial/v3/en/players/wgr/2022/rankings.json?api_key=rupvugmcybede53f3svuqqa8",
  dataType: 'json',
  success: function(json) {
    console.log("success");
    data = json.players;
    $('#myTable').DataTable({
      data: data,
      columns: [{
          data: 'id'
        },
        {
          data: 'first_name'
        }
      ]


    });
  },
  error: function(e) {
    console.log("error");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<table id="myTable">
  <thead>
    <tr>
      <th>id</th>
      <th>first name</th>
    </tr>
  </thead>

</table>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading