Table Headers from AJAX?

Table Headers from AJAX?

jsmythejsmythe Posts: 7Questions: 1Answers: 0

If I have data structured

{
"columns": [{"title": "Title1"}, {"title": "Title2"}],
"data": [ ["Data1", "Data2"], ["Data3", "Data4"] ]
}

like one of the DataTable.defaults aaData examples in jquery.dataTables.js (around line 9880), is there a way that the entire table (i.e., headers and data cells) can be dynamically built from the data using AJAX? BTW, I can provide metadata information in the columns section if that's allowed.

Answers

  • htwyfordhtwyford Posts: 23Questions: 9Answers: 1

    The FAQ states:

    Q. Can I define my columns in Ajax loaded JSON?
    A. This is not currently a native feature in DataTables (although it is likely to be added in future). Instead, you would need to load the JSON data using $.ajax and assign the column definition array using the columns option.

    So unfortunately, you can't define headers in Ajax. You must define your headers in the columns attribute of your DataTables initalization.

  • bindridbindrid Posts: 730Questions: 0Answers: 119
    edited June 2017

    You can if you call your ajax before you create your table.

    something like ( a lot of code left but you get the idea)

    $.ajax({
        url:"yourpage",
        success: function(response){
            // if you are calling this multiple times and the headers change you will 
           // have to destroy the DataTable and the table inner html
           $("#example").DataTable({data:response.data, columns:response.columns});
    })
    
  • jsmythejsmythe Posts: 7Questions: 1Answers: 0

    I tried it with and without "'s around data and columns but neither worked. Using dataTable instead of DataTable also didn't work. It does get the response as I can display it but no table is ever shown. I also have
    <table id="example" class="display" width="100%" cellspacing="0"></table>
    Is a different data response structure required or is something else wrong?

This discussion has been closed.