DataTables - Dynamic Columns From Ajax Data Source?
<p>I am trying to get DataTables to read the column names from an AJAX data source but it seems that there must be something that I must be missing here.</p>

<p>I made a fiddle <a href="https://jsfiddle.net/craigvt/oLrgjrvd/" rel="noreferrer">fiddle</a> in which I can manually define the data and columns that are being used by the table.</p>

<p>The table is declared in the HTML and there is no no need to define the column names (<code>&lt;thead&gt;..&lt;/thead&gt;</code>):</p>

<pre><code>&lt;table id="example" class="display table table-striped table-bordered" 
       cellspacing="0" width="100%"&gt;&lt;/table&gt;
</code></pre>

<p>In the JS we manually define the data:</p>

<pre><code>var data = [
    [ "Row 1 - Field 1", "Row 1 - Field 2", "Row 1 - Field 3" ],
    [ "Row 2 - Field 1", "Row 2 - Field 2", "Row 2 - Field 3" ],
];
</code></pre>

<p>Then manually define the column names or titles:</p>

<pre><code>var columns = [
    { "title":"One" },
    { "title":"Two" }, 
    { "title":"Three" }
];
</code></pre>

<p>Then when we initialise the table we simply pass the previously declared information across for DataTables to use: </p>

<pre><code>$(document).ready(function() {
  $('#example').DataTable( {
    dom: "Bfrtip",
    data: data,
    columns: columns
  });
});
</code></pre>

<p>Which results in:</p>

<p><a href="https://i.stack.imgur.com/JJCps.png" rel="noreferrer"><img src="https://i.stack.imgur.com/JJCps.png" alt="Resulting Table"></a></p>

<p>Now my question is how would I get this to work if the data is included in the <a href="https://datatables.net/examples/data_sources/ajax.html" rel="noreferrer">AJAX server side response</a>?</p>

<p>I have tried this in various ways and forms but nothing really seems to work out here and I am battling to find relative documentation on this.</p>

<p>For example if the server side processing sent back a JSON response which includes the column names at the end:</p>

<pre><code>{
  "data": [
    {
      "id": "1",
      "One": "Row 1 - Field 1",
      "Two": "Row 1 - Field 2",
      "Three": "Row 1 - Field 3"
    },
    {
      "id": "2",
      "One": "Row 2 - Field 1",
      "Two": "Row 2 - Field 2",
      "Three": "Row 2 - Field 3"
    }
  ],
  "options": [],
  "files": [],
  "columns": [
    {
      "title": "One",
      "data": "One"
    },
    {

      "title": "Two",
      "data": "Two"
    },
    {
      "title": "Three",
      "data": "Three"
    }
  ]
}
</code></pre>

<p>Given this is the response, I tried to configure DataTables to use an AJAX data source for the row information as follows:</p>

<pre><code>$(document).ready(function() {
  $('#example').DataTable( {
    dom: "Bfrtip",
    "ajax": '/test.php',
    columns: columns
  });
});
</code></pre>

<p>But obviously <code>columns</code> is undefined here.</p>

<p>So I get the column data before hand:</p>

<pre><code>function getPromise() {
  var deferred = $.Deferred();
  var dataUrl = document.location.origin+'/text.php';
  $.getJSON(dataUrl, function(jsondata) {
    setTimeout(function() {
      deferred.resolve(jsondata);
    }, 0);
  }).fail(function( jqxhr, textStatus, error ) {
    // ********* FAILED
    var err = textStatus + ", " + error;
    console.log( "Request Failed: " + err );
  });
  return deferred.promise();
}
// Get the columns
getPromise().done(function(jsondata) {
  columns = jsondata.columns;
  console.log(columns);
});
</code></pre>

<p>And pass it to DataTables as above. But this time all I get when running the example is an error in the console saying <code>TypeError: p is undefined</code>.</p>

<p>So then how could I make use of the dynamically generated columns that are being returned within the server side response? Is there not a simpler way to achieve this?</p>

<p>EDIT:</p>

<p>DataTables Editor code for server side processing / to generate the JSON response mentioned above:</p>

<pre><code>&lt;?php
// DataTables PHP library
require_once '/path/to/DataTables.php';

// Alias Editor classes so they are easy to use
use
  DataTables\Editor,
  DataTables\Editor\Field,
  DataTables\Editor\Format,
  DataTables\Editor\Mjoin,
  DataTables\Editor\Upload,
  DataTables\Editor\Validate;

// Build our Editor instance and process the data coming from _POST
$out = Editor::inst( $db, 'example' )
  -&gt;fields(
    Field::inst( 'id' )-&gt;set(false),
    Field::inst( '`One`' )-&gt;validator( 'Validate::notEmpty' ),
    Field::inst( '`Two`' )-&gt;validator( 'Validate::notEmpty' ),
    Field::inst( '`Three`' )-&gt;validator( 'Validate::notEmpty' )
  )
  -&gt;process( $_POST )
  -&gt;data();

// On 'read' remove the DT_RowId property so we can see fully how the `idSrc`
// option works on the client-side.
if ( Editor::action( $_POST ) === Editor::ACTION_READ ) {
    for ( $i=0, $ien=count($out['data']) ; $i&lt;$ien ; $i++ ) {
        unset( $out['data'][$i]['DT_RowId'] );
    }
}

// Create the thead data
if (count ($out) &gt; 0) {
  $columns = array();
  foreach ($out['data'][0] as $column=&gt;$relativeValue) {
    // Add all but the id value
    if ($column !== 'id') {
      // Add this column name
      $columns[] = array(
        "title"=&gt;$column,
        "data"=&gt;$column
      );
    }
  }
}
// Add the the thead data to the ajax response
$out['columns'] = $columns;
// Send the data back to the client
echo json_encode( $out );
</code></pre>