5

I want to get all the json from https://swapi.co/api/planets/?format=json data using REST API & jQuery plugin DataTable, but my problem is, it loads the data at first, but when I start typing in the search field provided by Datatable .. it says "No data available in table".

I've been searching this similiar problem, but I still can't find the solution. What I have tried is

My HTML file:

rest.html


<table id="tableSwapi" class="table table-striped">
         <thead>
            <tr>
                <th>Name</th>
                <th>Rotation Period</th>
                <th>Orbital Period</th>
                 <th>Diameter</th>
                 <th>Climate</th>
                 <th>Gravity</th>
                 <th>Terrain</th>
                 <th>Water Surface</th>
                 <th>Population</th>
            </tr>
         </thead>
         <tbody id="list-list">

         </tbody>
</table>

My script file:

script.js

$(document).ready(function () {
 $("#tableSwapi").dataTable();

$.ajax({
        url: 'https://swapi.co/api/planets/',
        type: 'get',
        dataType: 'json',
        success: function (result) {
            let daftar = result.results;
            var html = '';
            $.each(daftar, function (i, data) {             
                html += `<tr>
                            <td> ` + data.name + `</td>
                            <td>` + data.rotation_period + `</td>
                            <td>` + data.orbital_period + `</td>
                            <td>` + data.diameter + `</td>
                            <td> ` + data.climate + ` </td>
                            <td> ` + data.gravity + ` </td>
                            <td>` + data.terrain + `</td>
                            <td> ` + data.surface_water + `</td>
                            <td> ` + data.population + ` <br></td>
                        </tr>`;

                //This is selector of my <tbody> in my table
                $("#list-list").html(html);
            });
        }
    });
})

Any kind of help is appreciated. Thank you.

4
  • 1
    Would be better to insert the data itself through Datatable API then tell it to redraw. If you insert html yourself the plugin has no idea anything has changed. It stores the table state internally in order to know what rows to render based on sort, pagination , search etc Commented Mar 23, 2019 at 10:16
  • Where are you initializing datatable in your code? Commented Mar 23, 2019 at 10:52
  • I'm sorry, i just edited the script code. there you go. Commented Mar 23, 2019 at 10:53
  • @charlietfl ok thanks, i've figured it out, so i went to load the ajax first and second I loaded the DataTable() inside the setTimeout() function, so the I gave the time to let the DataTable knows if there are data rows in the table. Commented Mar 24, 2019 at 5:40

2 Answers 2

3

If you can use server side script then try the code like

PHP Code ajax.php

$url = "https://swapi.co/api/planets/?page=".($_GET['start']/$_GET['length']+1); 
if (isset($_GET['search']) && !empty($_GET['search'])) {
    $url .= "&search=".$_GET['search']['value'];
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_URL, $url);
$result = json_decode(curl_exec($ch),true);
$array = array
        (
            "draw" => $_GET['draw'],
            "recordsTotal" => $result['count'],
            "recordsFiltered" => $result['count'],
            "data" => $result['results'],
        );
echo json_encode($array);

Jquery Datatable Code

$('#tableSwapi').DataTable({
    "processing": true,
    "serverSide": true,
    "sPaginationType": "full_numbers",
    "order": [],
    "ajax": {
        "url": "ajax.php",
        "type": 'get',
        "dataType": 'json'
    },
    "columns": [
        { "data": "name" },
        { "data": "rotation_period" },
        { "data": "orbital_period" },
        { "data": "diameter" },
        { "data": "climate" },
        { "data": "gravity" },
        { "data": "terrain" },
        { "data": "surface_water" },
        { "data": "population" },
    ]
});
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah thanks but I'm trying to not use the server side script, Do you think there is any possibilty without using the server side script. Could you share your answer again? I appreciate it mate.
If you know everything about this API can you let me know how you can get the whole record at once by ajax. right now its providing 10 record per request.
2

I used your example and it's working properly.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
    
</head>
<body>
    <table id="tableSwapi" class="table table-striped">
        <thead>
            <tr>
                <th>Name</th>
                <th>Rotation Period</th>
                <th>Orbital Period</th>
                <th>Diameter</th>
                <th>Climate</th>
                <th>Gravity</th>
                <th>Terrain</th>
                <th>Water Surface</th>
                <th>Population</th>
            </tr>
        </thead>
        <tbody id="list-list"></tbody>
    </table>    
    <script
  src="http://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
    <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
    
    <script>
        $(document).ready(function () {
            $("#tableSwapi").dataTable();

            $.ajax({
                url: 'https://swapi.co/api/planets/',
                type: 'get',
                dataType: 'json',
                success: function (result) {
                    let daftar = result.results;
                    var html = '';
                    $.each(daftar, function (i, data) {
                        html += `<tr>
                                        <td> ` + data.name + `</td>
                                        <td>` + data.rotation_period + `</td>
                                        <td>` + data.orbital_period + `</td>
                                        <td>` + data.diameter + `</td>
                                        <td> ` + data.climate + ` </td>
                                        <td> ` + data.gravity + ` </td>
                                        <td>` + data.terrain + `</td>
                                        <td> ` + data.surface_water + `</td>
                                        <td> ` + data.population + ` <br></td>
                                    </tr>`;

                        //This is selector of my <tbody> in my table
                        $("#list-list").html(html);
                    });
                }
            });
        })


    </script>
</body>
</html>

Maybe a problem with Datatable plugin. Please check in inspect elements.

2 Comments

Is the search field working? I ran the code snippet, It loads the data at first. but when I started using the search field, the problem is still the same, same as I click the sort column.
ok thanks, i've figured it out, so i went to load the ajax first and second I loaded the DataTable() inside the setTimeout() function, so the I gave the time to let the DataTable knows if there are data rows in the table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.