Adding dynamic data to DataTables on the fly

I am currently developing a Python crawler that stores data in a mongoDB database. The goal is to dynamically load this data into a table without refreshing the entire page.

Here's the relevant part of my code:

var $tagsLabel = $("<lable>")
var $tagsInput = $("<textarea>");

/* Row details formatting function - customize based on your needs */
function format(d) {
    // `d` is the original data object for the row
    return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
        '<tr>' +
        '<td>Raw text:</td>' +
        '<td>' + d.Raw_html + '</td>' +
        '</tr>' +
        '</table>';
}

$(document).ready(function () {
    $table = $("#dataTable")
        .on("preInit.dt", function (e, settings) {
            $tagsLabel.append($tagsInput);
            $('.dataTables_tags').append($tagsLabel)
        })
        .on("init.dt", function (e, settings) {
            $tagsInput.tagEditor({
                delimiter: ', ',
                placeholder: 'Enter search tags ...',
                onChange: function (field, editor, tags) {
                    if (tags.length) {
                        if (tags.length > 1) {
                            $table.search(tags.join('|'), true, false).draw();
                        } else {
                            $table.search(tags[0]).draw();
                        }
                    } else {
                        $table.search('').draw(true);
                    }
                },
            });
        })
        .DataTable({
            "dom": '<l<"dataTables_tags"><t>ip>',
            "ajax": '/json-int',
            "columns": [
                {
                    "class": 'details-control',
                    "orderable": false,
                    "data": null,
                    "defaultContent": '',
                    width: "5px"
                },
                {"data": "Timestamp", width: "135px"},
                {"data": "Title"},
                {"data": "Url"},
                {"data": "domain"},
                {"data": "Type"},
                {"data": "Raw_html", "visible": false}
                //{"data": "Raw_html", "visible": false}

            ],
            "order": [[1, 'asc']]
        });


    // Add event listener for opening and closing details
    $('#dataTable tbody').on('click', 'td', function () {
        var tr = $(this).closest('tr');
        var row = $table.row(tr);

        if (row.child.isShown()) {
            // This row is already open - close it
            row.child.hide();
            tr.removeClass('shown');
        } else {
            // Open this row
            row.child(format(row.data()), 'no-padding').show();
            tr.addClass('shown');

        }
    });

    $('#dataTable tbody').on('click', 'td > button', function (e) {
        alert('Tada!');
        return false;
    });
});



<table id="dataTable" class="table table-striped table-hover table-bordered table-condensed"
                           style="width: 100%; font-size: 12px" role="grid">
                        <thead>
                        <tr>
                            <th></th>
                            <th>Timestamp</th>
                            <th>Title</th>
                            <th>URL</th>
                            <th>Domain</th>
                            <th>Page Type</th>
                        </tr>
                        </thead>
                        <tfoot>
                        <tr>
                            <th></th>
                            <th>Timestamp</th>
                            <th>Title</th>
                            <th>URL</th>
                            <th>Domain</th>
                            <th>Page Type</th>
                        </tr>
                        </tfoot>
                    </table>

The function I'm attempting to use for updating the table dynamically:

    function updateTable() {
    $(document).ready(function () {
        var t = $('#dataTable').DataTable();
        $.ajax({
            type: "GET",
            url: "/json",
        }).done(function (data) {

            var parsed = JSON.parse(data);

             parsed.forEach((obj, i) => {
                t.row.add([
                    obj.Timestamp,
                    obj.Title,
                    obj.Url,
                    obj.domain,
                    obj.Type,
                    obj.Raw_html
                ]).draw(false);
            });
        }).fail(function (jqXHR, textStatus, errorThrown) {
            console.log(jqXHR, textStatus, errorThrown);
        })
    });
}
setInterval(updateTable, 5000);

While the table loads successfully and data is loaded when the page refreshes, I encounter an error every time the dynamic update function runs:

DataTables warning: table id=dataTable - Requested unknown parameter 'Timestamp' for row 0, column 1. For more information about this error, please see http://datatables.net/tn/4

I have provided an example of the data intended to be loaded dynamically into the table:

I hope someone can guide me in the right direction.

EDIT: Apologies if my question was unclear. When the page initially loads, the data is populated. However, I aim to add new rows to the table whenever there is new data available from /json each time it is requested.

Answer №1

No need to reinvent the wheel, the solution is already available at https://datatables.net/examples/data_sources/ajax.html. All you have to do is enhance your DataTable initialization with the appropriate parameter:

var t = $('#dataTable').DataTable({
    ajax: '/url/to/script/feeding/data',
    ...
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The function $.getJSON is unable to interpret an array

I'm encountering an issue while attempting to retrieve data from a json file (an array of objects) using $.getJSON. The problem is that the "success" function isn't being executed, despite it working when the json contains only one object. What c ...

What is the best way to change PHP database information into JSON format while using custom titles for each column?

Is it possible to convert PHP data sent from a controller to a view into JSON objects with new titles, and then wrap it in a script tag? I want the data to have the same titles as specified in my view, even though the database titles are different. Contro ...

What is the process for changing just the month and year portions of a date?

Imagine having a fixed date of 28-05-2012. How can I modify it so that only the month changes when it reaches the 28th of the new month? For example, from 28-05-2012 to 28-06-2012, then to 28-07-2012, and so forth. Additionally, once the year hits 2013, I ...

Is the functionality of Array.prototype.indexOf() different when used in React.js?

Can someone help me understand the inner workings of this code? I am utilizing Array.prototype.indexOf() to retrieve the index of the state array in order to update it. The instructions suggest passing an object as a parameter to indexOf(), but my unders ...

Calculating the percentage in a jQuery Slider

For a while now, I've been using var slideWidth = 420; to set the width of sliders and then $('#slideInner').css('width', slideWidth * numberOfSlides); to calculate the total width of all sliders effectively in pixels. An Issue Ar ...

Link a PHP variable to a JavaScript variable

Is there a way to set the value of a JavaScript variable using a PHP variable? $(function(){ $("select[name=myselectlist]").change(function(){ var id = $(this).val(); if(id != 0) { $.post("ajax.php", {"id":id}, func ...

Conditional rendering of a template can be achieved with GoJS

Is it possible to render a specific part of a template based on the value of an item in a node data object? If the value is true, then I want to render this part of the template: $(go.TextBlock, { row: 1, column: 0, font: '12px \'Open Sans& ...

What is the appropriate way to retrieve an array that has been stored in the this.state property?

https://i.stack.imgur.com/y9huN.jpgAs a newcomer to react, I have been exploring the react documentation on making Ajax calls. While the docs make it seem simple to retrieve JSON information and set it to a state variable, I've encountered some challe ...

What is the best way to save this JSONArray into an ArrayList?

I'm facing issues while trying to build an ArrayList from a retrieved JSONArray through an API Get request. The list I'm receiving is empty. What mistake am I making in my approach? The specific JSONArray I want to extract is named "recipes". My ...

Leveraging AngularJS for a Windows store app

After attempting to integrate AngularJS into my Windows store application, I came across a few recommended solutions: Unfortunately, these solutions did not work as expected. While I didn't encounter the Unable to add dynamic content error, AngularJS ...

How can I determine if there is text contained within an HTML tag?

Imagine a scenario where I want to retrieve all text from a specific HTML tag: Here is the example HTML: <div id="container"> <div id="subject"> <span><a></a></span> </div> </div> var ...

"Enhancing a many-to-many relationship with indexing in TypeORM: A step-by-step guide

Is it possible to add an index to the relation columns when creating a many-to-many relationship in typeORM entities? @Entity() export class Tag { @Column() id: number //@Index() does not work here... @ManyToMany(() => Todo, (todo) => todo ...

Trouble with launching Jasmine tests within define block in compiled Typescript

Currently, I am immersed in a testing project that involves setting up a pure Javascript Jasmine Karma environment to test a pre-compiled Typescript setup. Despite my efforts, I am facing an issue where the test cases refuse to start running. While the co ...

Utilize Backbone.js to organize and structure JSON data by populating it into nested collections and models within

I am new to Backbone.js and struggling with a complex problem. I need to save a form with infinite fields, some of which also have infinite options. My concern is that I started with a JSON response instead of building the models/collections first. Here&ap ...

Tips for handling the accent mark (diacritic mark)

My primary language is Spanish, which means I use accent marks quite frequently (á, é...). When I need to type them out, I resort to using &aacute;, &eacute;, and so on. However, I'm facing an issue when trying to compare two sentences in m ...

Optimizing Angular for search engines: step-by-step guide

Regarding Angular SEO, I have a question about setting meta tags in the constructors of .ts files. I have implemented the following code: //To set the page title this.titleServ.setTitle("PAGE TITLE") //To set the meta description this.meta.addTag ...

Guide on obtaining the Parent hierarchy within the Tree View component

Hello! I am working with a tree object that has parent and nested children, displayed with checkboxes. When a child is checked, I need to retrieve the names of the parent and grandparent up to the entire hierarchy. Below is my JSON data: { [ ...

An insightful guide on effectively binding form controls in Angular using reactive forms, exploring the nuances of formControlName and ngModel

Here is the code snippet: list.component.html <form nz-form [formGroup]="taskFormGroup" (submit)="saveFormData()"> <div nz-row *ngFor="let remark of checklist> <div nz-col nzXXl="12" *ngFor="let task of remark.tasks" styl ...

"Having trouble with Set-Cookie Response Header not setting the cookie? It could be due to

My webpage is located at: http://localhost:4201/login When a user clicks on login, it sends a request to: http://localhost:4201/api/login/authenticate This request is then proxied to: The response from the proxy contains a set-cookie header with the f ...

How can I locally include an ID in an HTML tag using Angular?

Hey there, I'm not facing any issue currently, but I have a question out of curiosity. Is it possible in Angular to locally add an ID to an HTML tag? I want this ID to be accessible only by the component that defines it. My intention is to set the ID ...