PlusMagi's Blog By Pitt Phunsanit TypeScript Using TypeScript with DataTables for Enhanced Data Management

Using TypeScript with DataTables for Enhanced Data Management

After integrating jQuery and Font Awesome, it’s time to dive into practical usage with DataTables.net. This guide will walk you through the process of setting up DataTables using TypeScript, including the necessary imports and configurations.

Step 1: Install DataTables

First, you need to install DataTables and its CSS using npm. Run the following command in your terminal:

SQL

npm install datatables.net-dt

Step 2: Configure TypeScript

Open your TypeScript file located at SourceCode/resources/js/app.ts and add the following imports:

SQL

import 'datatables.net';
import 'datatables.net-dt';
import 'datatables.net-dt/css/dataTables.dataTables.min.css';

Step 3: Initialize DataTables

Create a JavaScript file, for example, SourceCode/public/assets/tickets.list.js, and add the following code to initialize DataTables:

SQL

$(document).ready(function () {
    $('#tickets-list').DataTable({
        ajax: {
            headers: {
                'X-CSRF-TOKEN': csrf_token,
                'X-Requested-With': 'XMLHttpRequest'
            },
            type: 'GET',
            url: base + '/tickets'
        },
        columns: [
            {
                orderable: false,
                render: function (data, type, row, meta) {
                    return parseInt(meta.row) + parseInt(meta.settings._iDisplayStart) + 1;
                },
                title: 'No.',
                width: '10px'
            },
            {
                orderable: false,
                render: function (data, type, row, meta) {
                    return '<input type=checkbox value="' + row.DISTRICT_CODE + '">';
                },
                title: '<input class="checkAll" type="checkbox">',
                width: '10px',
            },
            {
                data: 'id',
                name: 'id',
                orderable: true,
                title: 'ID',
                width: '10px'
            },
            {
                data: 'category_id',
                orderable: true,
                render: function (data, type, row) {
                    return row.category;
                },
                title: 'Category'
            },
            {
                data: 'vessel_id',
                orderable: true,
                render: function (data, type, row) {
                    return row.vessel;
                },
                title: 'Vessel'
            }
        ]
    });
});

Conclusion

By following these steps, you can successfully integrate DataTables into your TypeScript project. This setup allows for dynamic data management with advanced features such as sorting, searching, and pagination, enhancing the user experience of your application.