dynamically loaded table

dynamically loaded table

kiwiskiwis Posts: 15Questions: 10Answers: 0

I'm using JS fetch to get a HTML page which contains my table. I'm adding this into my main page.

Previously the page was "included" via PHP so my Datatables JS code would go on my main page.

Now that I'm using fetch to get my table it's not working. I don't think detecting my table.

Are there any options?

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    We're happy to take a look, but as per the forum rules, please link to a test case - a test case that replicates the issue will ensure you'll get a quick and accurate response. Information on how to create a test case (if you aren't able to link to the page you are working on) is available here.

    Cheers,

    Colin

  • kiwiskiwis Posts: 15Questions: 10Answers: 0

    Here's where I'm at.

    fetch('myJSONfile.php').then(function(response) {
    return response.json().then(function(text) {
    data = JSON.parse(text);

    /* HELP - NEED TO KNOW HOW TO LOOP JSON OBJECT AND ADD ROWS */
    });
    });

    I just can't find any where how to do this, I want to create HTML links using ID's and names from different nodes in my JSON

  • kiwiskiwis Posts: 15Questions: 10Answers: 0
    edited April 2021
            return response.json().then(function(data) {
                for(var i = 0; i < data.length; i++) {
                    var obj = data[i];
                    console.log(obj.id);
                    t.row.add([obj.id, '','','','','','','','','']);
                }
    

    Here's an update, I can get the ID in the console log but not in the table.

  • kthorngrenkthorngren Posts: 21,443Questions: 26Answers: 4,974

    t.row.add([obj.id, '','','','','','','','','']);

    Have you assigned t to the Datatable's API, for example: var t = ('#myTable').DataTable();?

    Looks like you are getting an array of objects in the Ajax response. I suggest you use rows.add(), ie t.rows.add( data ), instead of the loop. And use columns.data to define your object based data. See this example with objects:
    https://datatables.net/examples/ajax/objects.html

    Maybe you can also just use the ajax option instead of using fetch().

    Kevin

This discussion has been closed.