Search code examples
javascriptjquerydatatable

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

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>