9

I am using Datatables with server_processing to get data, the main issue is i dont want to specify the name of the columns in html (<th width="25" id ="th1">id</th>), I want to create columns dynamically when getting data by ajax.

My code is :

$('#table').dataTable( {

    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": "server_processing.php?db="+pid+"&table="+id+"", //pid is the name of database and id the name of the table
     "bJQueryUI": true,
    "sPaginationType": "full_numbers"

} );             

2 Answers 2

5

"Although DataTables can obtain information about the table directly from the DOM, you may wish to give DataTables specific instructions for each individual column. This can be done using either the aoColumnDefs parameter, or aoColumns and the object information given for each column."http://datatables.net/usage/columns

Something like:

html

<table class="display" id="table"></table>

js

$("#table").dataTable({
    bJQueryUI:true,
    aoColumns:[
        {mDataProp:"foo",sTitle:"Foo Title"},
        {mDataProp:"bar",sTitle:"Bar Title"}
    ],
    fnServerData: function( sUrl, data, fnCallback){
        $.get('data.php', function(res) {
            fnCallback({  // process results to match table format
                "sEcho":config.sEcho,
                "iTotalRecords":res.data.total || res.data.count,
                "iTotalDisplayRecords":res.data.count || res.data.total,
                "aaData":res.data.list
            })
        });
    }
})

Where data.php is

{
    data:{
        total:200,
        count:3,
        list:[
            {foo:"Foo 1",bar:"Bar 1"},
            {foo:"Foo 2",bar:"Bar 2"},
            {foo:"Foo 3",bar:"Bar 3"},
        ]
    }
}

There's also a good summary of setting this up here: http://datatables.net/usage/options#aaData

Sign up to request clarification or add additional context in comments.

2 Comments

This is a nice answer, however it does not answer the actual OP. He is asking about the column names and column specification and you are answering about the data.
Hey Giovanni, thanks for the comment, but out of curiosity, did you miss the first part of the post? aoColumns describes the column names. I added the JSON data for clarity.
0

You can create HTML table as string at server side then return the string in ajax call like below.

    StringBuilder tblString = new StringBuilder();
if (ds != null && ds.Tables != null && ds.Tables.Count > 0)
                    {
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            #region FormateTable
                            tblString.Clear();

                            tblString.Append("<table id='datatable1' class='table table-striped table-hover'>");
                            tblString.Append("<thead>" +
                                         "<tr> ");
                            foreach (var col in ds.Tables[0].Columns)
                            {
                                tblString.Append("<th>" + col.ToString() + "</th>");
                            }

                            tblString.Append("</tr>" +
                                      " </thead><tbody>");
                            foreach (DataRow dr in ds.Tables[0].Rows)
                            {
                                tblString.Append("<tr>");

                                for (int colIndex = 0; colIndex < 
ds.Tables[0].Columns.Count; colIndex++)
                                {
                                    tblString.Append("<td>");
                                    tblString.Append(dr[colIndex] != null ? 
dr[colIndex].ToString() : null);
                                    tblString.Append("</td>");
                                }
                                tblString.Append("</tr>");
                            }

                            tblString.Append("</tbody></table>");

                            #endregion
                        }
                    }
Then return string builder like below:
return Json(new
            {
                message = msg,
                List = tblString.ToString(),
            }, JsonRequestBehavior.AllowGet);

Now use in AJAX:

 $.ajax({
                url: '@Url.Action("GetData", "MyController")',
                type: "POST",
                data: addAntiForgeryToken({ Query: Query }),
                dataType: 'JSON',
                success: function (data) {
                    if (data.message == "Success") {
                    $('#itemtable').html(data.List);
                    return false;
                    }
                },
                error: function (xhr) {
                    $.notify({
                    message: 'Error',
                    status: 'danger',
                    pos: 'bottom-right'
                    });
                    }
                });
            }

HTML code:

 <div class="panel-body">
                <div class="table-responsive" style="width:100%; height:564px; overflow-y:scroll;">
                    <div id="itemtable"></div>
                </div>
            </div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.