Valtana
Valtana

Reputation: 23

Empty table body in jQuery DataTables

I'm a newbie to jQuery, so, please, don't judge me for my dumb question. What I'm trying to achieve is fill datatable with exchange rates, sourced by API.

So, I managed to construct datatable, but its body is empty and there're no errors in the console, it's just "loading..." message where my data is supposed to be.

Searching for similar topics just didn't get any results. I would be thankful for your help, because I'm banging my head against that wall for 2 days already.

<head> 
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
  <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>       
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"> 
</head> 
<body> 
  <table id="rates"></table> 
</body>
var key = '8366e7a49e014c729111a0ac6e5c7d9d';
var url = 'https://openexchangerates.org/api/latest.json?app_id=';
var dataTable = $('#rates').DataTable({
  sDom: 't',
  ajax: {
    url: url + key
  },
  columns: [{
    title: 'currency'
  },{
    title: 'rate'
  }]
});

Upvotes: 1

Views: 824

Answers (1)

user3307073
user3307073

Reputation:

Seems like your data is structured improperly. Each data entry must correspond to DataTables row, so your code should be something like:

var key = '8366e7a49e014c729111a0ac6e5c7d9d';
var url = 'https://openexchangerates.org/api/latest.json?app_id=';

var dataTable = $('#rates').DataTable({
  sDom: 't',
  ajax: {
    url: url+key,
    dataSrc: function(data){
        let apiData = [];
        $.each(data.rates, function(index, entry){
          apiData.push({currency:index, rate:entry});
        });
        return apiData.slice(0,10);
      }
    },
    columns: [
      {title:'currency', data:'currency'},
      {title:'rate', data:'rate'}
    ]
});
<!doctype html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
  <table id="rates"></table>
</body>
</html>

Upvotes: 2

Related Questions