Is there a way to have two sources of data in a Datatable?

Viewed 21

I have a Datatable which I am getting JSON data from an API using a URL. I have made a custom post/get URL which I want to replace the current Datatable with the one I want. I Understand when the page loads, the Datatable automatically loads the table using the URL provided so now what I want is to make an AJAX call to another URL to get custom data but in the same format as my table then redirect that JSON data and fill in into the same table. Is this in anyway possible? Here is my Datatable:

<script>
    $(document).ready(function () {
        $("#documentsDatatable").DataTable({
            language: {
                "emptyTable": "No Documents found"
            },
            dom: 'lBfrtip',
            "responsive": false, "autoWidth": true,
            "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
            buttons: [
                {
                    extend: 'pdf',
                    title: 'Documents',
                    exportOptions:
                    {
                        columns: [2, 1, 4]
                    }
                },
                {
                    extend: 'excel',
                    title: 'Documents',
                    exportOptions:
                    {
                        columns: [2, 1, 4]
                    }
                },
                {
                    extend: 'csv',
                    title: 'Documents',
                    exportOptions:
                    {
                        columns: [2, 1, 4]
                    }
                }

            ],
            "processing": true,
            "serverSide": true,
            "order": [[4, 'asc']],
            "filter": true,
            "ajax": {
                "url": '@TempData["api"]api/Document/Documents',
                "headers": {
                    'Authorization': 'Bearer @HttpContextAccessor.HttpContext.Session.GetString("token")',
                    'Access-Control-Allow-Origin': '*'
                },
                "type": "POST",
                "datatype": "json"
            },
            "columnDefs": [{
                "targets": [0, 1],
                "visible": false,
                "searchable": true
            }],
            "columns": [
                { "data": "name", "name": "Name", "autoWidth": true },
                { "data": "name", "name": "Name", "autoWidth": true },
                {
                    "render": function (data, type, full, meta) {

                            return "<a href='Documents/Check/" + full.id + "'><span class='badge bg-primmary'><h5 title='" + full.name + "'>" + full.name.substring(0, 20) + "</h5></span></a>";
                    }
                },
                {
                    data: "created_at",
                    "render": function (value) {
                        if (value === null) return "";
                        return moment(value).format('DD/MM/YYYY');
                    }
                },
                {
                    "render": function (data, type, full, meta) {
                        return "<p title='" + full.createdBy.firstName.concat(" ", full.createdBy.lastName) + "'>"+ full.createdBy.email +"</p>"
                    }
                },
                {
                    "render": function (data, type, full, meta) {
                        return "<a href='Documents/Tag/" + full.id + "&" + full.name + "' class='btn btn-outline-success btn-link'><i class='fas fa-plus fa-xl'></i> Add</span></a>";
                    }
                },
                {
                    "render": function (data, type, full, meta) {
                        return "<a href='/Versioning/Versions/" + full.id + "' class='btn btn-outline-success btn-link' title='Versions'><i class='fas fa-code-branch fa-xl'></i> <span id='badge' class='badge badge-secondary'>" + full.versionCount + "</span> </a>";
                    }
                }
            ]
        });
    });
</script>

Above I am fetching the data without a problem and now I am making the below call to a URL to get the data which I can receive as JSON so how can I get this data into the same datatable and clear the previous?

    <script>
    function advancedSearch() {
        var document_type = document.getElementById("document_type").value;
        var date_from = document.getElementById("date_from").value;
        var date_to = document.getElementById("date_to").value;
        console.log(document_type);
                    $.ajax({
        type: 'POST',
        datatype: 'json',
        url: "@TempData["api"]api/Document/AdvancedSearch",
        headers: {
            'Authorization': 'Bearer @HttpContextAccessor.HttpContext.Session.GetString("token")',
            'Access-Control-Allow-Origin': '*'
        },
        data: { document_type: document_type, date_from: date_from, date_to: date_to},
        success: function () {
            alertify.set('notifier', 'position', 'top-center');
            alertify.success('Results are ready');
            //$('#documentsDatatable').DataTable().ajax.reload();

        },
        error: function () {

            alertify.set('notifier', 'position', 'top-center');
            var msg = alertify.error('Failed to fetch documents', 10);
            $('body').one('click', function () {
                msg.dismiss();
            });
            //setInterval('location.reload()', 1500);
            $('#documentsDatatable').DataTable().ajax.reload();

        }
    })
        }
</script>
1 Answers

You can use the ajax.url option to change the URL and reload the data, but this makes a GET request and you are using POST with additional headers.

One way to achieve what you want is to make the ajax property a function and to load your data from a local array.

All this is made easier if you also asign your datatable instance to a variable

let datatableArray = [];

const table = $("#documentsDatatable").DataTable({
    ajax: function(data, callback) {
        callback({data: datatableArray });
    }
});

Then when you make your server request and get a response you update the local array and tell DataTables to refresh.

function advancedSearch() {
    $.ajax({
        url: "@TempData["api"]api/Document/AdvancedSearch",
        method: 'POST',
        data: data,
        dataType: 'json',
        success: response => {
            datatableArray = response.data;
            table.ajax.reload();
        }
    });
}

Please note that this will initially start DataTables with an empty table. If you want to start with some default data you should call your advancedSearch() function with some default values on page load.

For more reading, here is a discussion that uses a similar technique, but instead it sets ajax.data as a function in order to change the parameters without changing the URL.

Related