Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return all column names/titles (and avoid "TypeError: table.columns(...).names is not a function")?

I have a very similar question to this one.

I create a datatable, then the user can use the search function, click a button and the selected data will then be sent to another function where it is further processed. Initializing the table works fine, also sending the selected data works as intended. However, I fail to access the column names correctly.

That's the datatables version I use:

 <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js" type="text/javascript"></script>

A bit of background: By clicking on a link (#calculate), a table is created and the column headers look fine, e.g. like this:

enter image description here

The user can then select entries (here 88), and the filtered data are then sent back using a second link (#send_data). The data used to initialize the column headers look like this (taken from console.log(data.columns);):

[…]
0: Object { name: "C1", title: "C1", sName: "C1", … }
1: Object { name: "C2", title: "C2", sName: "C2", … }
length: 2
__proto__: Array []

and I can also access table.columns(), however, when I try table.columns().names() or table.columns().title() I receive

TypeError: table.columns(...).names is not a function.

How can I access and pass the displayed column headers i.e. what goes to col_names in the code below?

The relevant code looks as follows:

<script type="text/javascript">
  $(document).ready(function() {
    var table = null;
    $('#calculate').bind('click', function() {
      $.getJSON('/_get_table', {
        a: $('#a').val(),
        b: $('#b').val()
      }, function(data) {
      console.log(data.columns);
        $("#elements").text(data.number_elements);
        if (table !== null) {
          table.destroy();
          table = null;
          $("#a_nice_table").empty();
        }
        table = $("#a_nice_table").DataTable({
          data: data.my_table,
          columns: data.columns
        });
      });
      return false;
    });
    $('#send_data').bind('click', function() {
        //console.log(table.columns());
        //console.log(table.columns().title());
        //console.log(table.columns().names());
      $.getJSON('/_selected_data', {

        sel_data: JSON.stringify(table.rows( { filter : 'applied'} ).data().toArray()),
        col_names: //what goes here?

      }, function(data) {
        alert('This worked')
      });
      return false;
    });
  });
</script>
like image 373
Cleb Avatar asked Sep 08 '25 10:09

Cleb


1 Answers

Here is a possible solution:

table.columns().header().toArray().map(x => x.innerText)

I used the API docs from DataTable. Replacing innerText with innerHTML also works.

like image 187
Scratch'N'Purr Avatar answered Sep 11 '25 02:09

Scratch'N'Purr