Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display API data from url with jquery datatable

I'm setting up a "statistic" page for my FiveM's server website, and I need help about how to display data with Jquery Datatables

I don't know anything about API, so i tried few things with PHP, but nothing really usefull :/

Here is my code:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>test-astos</title>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
  </head>
  <body>

    <table id="table_id" class="display">
        <thead>
            <tr>
                <th>Column 1</th>
                <th>Column 2</th>
            </tr>
        </thead>
        <tbody>
            <!-- data -->
        </tbody>
    </table>


    <script type="text/javascript">
    $(document).ready( function () {
      $('#table_id').DataTable({
        $.ajax({
          url : 'https://api.top-serveurs.net/v1/servers/SC4VCSEUS3/players-ranking',
          type : 'GET',
          dataType : 'json',
             success : function(json, statut){ // code_html contient le HTML renvoyé
             }
        });
      });
    });
    </script>

  </body>
</html>

I would like to display those data (https://api.top-serveurs.net/v1/servers/SC4VCSEUS3/players-ranking) with Jquery datatables.

Thanks :).

like image 259
tholeb Avatar asked Mar 15 '26 02:03

tholeb


1 Answers

First You forget to use jQuery CDN see in the example. and use like this.

<table id="table_id" class="display">
    <thead>
        <tr>
            <th>Votes</th>
            <th>Player Name</th>
        </tr>
    </thead>
    <tbody>
        <!-- data -->
    </tbody>
</table>


<script type="text/javascript">
$(document).ready( function () {

    $.ajax({
        url : 'https://api.top-serveurs.net/v1/servers/SC4VCSEUS3/players-ranking',
        type : 'GET',
        dataType : 'json',
        success : function(data) {
            bindtoDatatable(data.players);
        }
    });



});

function bindtoDatatable(data) {
        var table = $('#table_id').dataTable({
            "bAutoWidth" : false,
            "aaData" : data,
            "columns" : [ {
                "data" : "votes"
            }, {
                "data" : "playername"
            } ]
        })
    }
</script>
like image 142
Syed Naeem Tariq Avatar answered Mar 17 '26 16:03

Syed Naeem Tariq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!