How to prepare server-side data for a footer row?

How to prepare server-side data for a footer row?

dannerfrdannerfr Posts: 4Questions: 2Answers: 0

DataTables 2.3.2
Firefox 140.0.4

Hi there!

I compute totals on the server myself. DataTables should just display these values in a dedicated footer row rather than doing the maths itself. Of course, I read
* https://datatables.net/reference/option/columns.data
* https://datatables.net/examples/advanced_init/footer_callback.html
* https://datatables.net/reference/api/column().footer()
* and all server-side processing examples, yet it's unclear how to put the data together on the server so DataTables doesn't treat all of it as a <tbody> row but some pieces as a <tfoot> row instead?

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 22,162Questions: 26Answers: 5,102

    Make your calculations server side then add those as an object to the JSON response. Use the xhr event to get that object from the JSON resonse using the json parameter thne populate the appropriate footer cells.

    Kevin

  • allanallan Posts: 64,756Questions: 1Answers: 10,716 Site admin

    Kevin is spot on as always. A small addition is to make use of column().footer() to get the footer node so you can write the data from the JSON data into it.

    As a trivial example writing into a single footer cell, from a footers array in the JSON response:

    table.on('xhr', function (e, s, json) {
      table.column(0).footer().innerHTML = json.footers[0];
    });
    

    Allan

  • dannerfrdannerfr Posts: 4Questions: 2Answers: 0

    Thank you Kevin and Allan :)

    I had to create an ordinary data row with my server-side calculated totals hidden underneath. In order to avoid that dummy row from being displayed I had to call json.data.splice(...) in the event handler to remove it after extracting the totals and updating <tfoot> with them. It works but It looks clumsy :/ I bet you would have solved it more elegantly, wouldn't you?

    Frank

  • allanallan Posts: 64,756Questions: 1Answers: 10,716 Site admin
    Answer ✓

    Good job on getting it to work. Personally I would suggest your JSON data structure should be something like:

    {
      "data": [
        // rows...
      ],
      "footer": [
        // info for each cell...
      ]
    }
    

    which I think would provide better separation of concerns and be more maintainable, but there are many ways of doing these things!

    Allan

Sign In or Register to comment.