Priyank
Priyank

Reputation: 1174

jQuery datatable append th before it initialize

<table cellpadding="0" cellspacing="0" border="1" class="display" id="FormsData" style="margin-bottom:5px;">
    <thead>
        <tr id="thFormsData"> 

        </tr>
        <tr>
        </tr> 
    </thead>
    <tbody>
        <tr>
            <td class="dataTables_empty">
                Loading data ...
            </td>
        </tr>
    </tbody>          
</table>

Above is the table structure for jQuery datatable. and I am using below code to fill it.

$(document).ready(function() { 
   $('#FormsData').dataTable({
        "sDom": 'T<"clear">lfrtip',
        "bProcessing": true,
        "bServerSide": true,
        "sAjaxSource": "GetJsonData.aspx?FormKey=" + getQuerystring("FormKey", "") + "&FormData=Get"
  )}
)}

Now problem is that in this way I have to define th in table structure which jQuery datable is using as columns. But in my case I want to append th dynamically to the table before it initialize.

I want to append th based on json data which I get from GetJsonData.aspx file. Its defined in "sAjaxSource": "GetJsonData.aspx ..."

Upvotes: 0

Views: 2160

Answers (2)

Pehmolelu
Pehmolelu

Reputation: 3564

Have seen fnHeaderCallback function ?

This function is called on every 'draw' event, and allows you to dynamically modify the header row.
This can be used to calculate and display useful information about the table.

"fnHeaderCallback": function( nHead, aasData, iStart, iEnd, aiDisplay )

EDIT:

So your problem is that you want to create the th depending on the data you get via ajax but do that before initializing? Then you cant get the data in the initializing like you have in that code. I suggest using user827431 answer then.

Upvotes: 0

martin
martin

Reputation: 2493

There is a good example of loading dynamically from an JS array http://www.datatables.net/examples/data_sources/js_array.html

Here you need only to replace the static data with the data returned from the webservice.

var url = "GetJsonData.aspx?FormKey=" + getQuerystring("FormKey", "") + "&FormData=Get";

$.getJSON(url, function(data) {
    //test response and manipulate structure if necissary

    $('#example').dataTable( {
        "aaData":data,
        "aoColumns": [
            { "sTitle": "Engine" },
            { "sTitle": "Browser" } // etc...
        ]
    });
});

The aoColumns will also allow you to dynamically render the columns.

Upvotes: 1

Related Questions