Search code examples
jquerydatatablegoogle-apigoogle-drive-apigoogle-api-js-client

Using jQuery Datatable in Google Drive API


I'm working on how to implement jQuery Datatable to display data like this http://prntscr.com/s39fcm you can check its working on this website http://sharer.pw

My code:

function listFiles() {
gapi.client.drive.files.list({
    'pageSize': 10,
    'fields': "nextPageToken, files(id, name, mimeType)"
}).then(function(response) {

    var files = response.result.files;
    if (files && files.length > 0) {


        for (var i = 0; i < files.length; i++) {
            var file = files[i];


            var dataSet = [
                [file.name, file.mimeType, "<input type='checkbox'/>", "<div class='btn-group'><a class='btn btn-primary' href='#'>Share</a><a class='btn btn-danger'>Delete</a></div>"]
            ];


        }
        $('#example').DataTable({
            data: dataSet,
            columns: [
                { title: "File Name" },
                { title: "Type" },
                { title: "Select" },
                { title: "Action" }
            ]
        });
    } else {
        console.log('No files found.');
    }

});

this code is only returning one record! I also tried to put the $('#example').DataTable({..}); inside for loop but its says this

http://prntscr.com/s39oyn


Solution

  • I've just resolved the issue on my own. this below code works like charm! :)

    In HTML:

    <table id="tab">
    <thead>
        <tr>
            <th>File Name</th>
            <th>Type</th> 
            <th>Select</th>
            <th>Action</th>
        </tr>
    </thead>
    

    in JS file:

    function listFiles() {
    gapi.client.drive.files.list({
        'pageSize': 10,
        'fields': "files(id, name, mimeType)"
    }).then(function(response) {
    
        var files = response.result.files;
        if (files && files.length > 0) {
    
            for (var i = 0; i < files.length; i++) {
                var file = files[i];
    
                 $('#tab').append($('<tr>')
                  .append($('<td>').append(file.name))
                  .append($('<td>').append(file.name))
                  .append($('<td>').append(file.name))
                  .append($('<td>').append(file.name))
                );
            }
    
                $('#tab').DataTable();
    
        } else {
            console.log('No files found.');
        }
    });
    }