0

I have a sharepoint 2013 list with some items, I need to put it into DataTable dynamically, is possible create the html table automatically?

1

We can use REST API to get list items, then using jQuery datatable to show the items. The example code below for your reference.

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>        
<script type="text/javascript" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>     
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">    
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.12/css/dataTables.jqueryui.min.css">      
<script type="text/javascript">
$(document).ready(function() {    
    loadItems();
});
function loadItems() {    
    var siteUrl = _spPageContextInfo.siteAbsoluteUrl;    
    var oDataUrl = siteUrl + "/_api/web/lists/getbytitle('EmployeeInfo')/items?$select=Title,Position,Office,Age,Joining_x0020_date";    
    $.ajax({    
        url: oDataUrl,    
        type: "GET",    
        dataType: "json",    
        headers: {    
            "accept": "application/json;odata=verbose"    
        },    
        success: mySuccHandler,    
        error: myErrHandler    
    });    
}    

function mySuccHandler(data) {    
    try {             
        $('#table_id').DataTable({             
            "aaData": data.d.results,    
            "aoColumns": [  
            {    
                "mData": "Title"    
            },   
            {    
                "mData": "Position"    
            },   
            {    
                "mData": "Office"    
            },   
            {    
                "mData": "Age"    
            },  
            {    
                "mData": "Joining_x0020_date"    
            }             
            ]    
        });    
    } catch (e) {    
        alert(e.message);    
    }    
}    

function myErrHandler(data, errMessage) {    
    alert("Error: " + errMessage);    
}   
</script>
<div>    
<table id="table_id" class="display" cellspacing="0" width="100%">    
    <thead>    
        <tr>    
            <th>Name</th>    
            <th>Position</th>    
            <th>Office</th>    
            <th>Age</th>    
            <th>Joining Date</th>            
        </tr>    
    </thead>    
    <tfoot>  
        <tr>    
            <th>Name</th>    
            <th>Position</th>    
            <th>Office</th>    
            <th>Age</th>    
            <th>Joining Date</th>                   
        </tr>   
    </tfoot>    
</table>    
</div> 

Reference: Using jQuery DataTable To Display SharePoint 2013 List Data On SharePoint Site Pages

  • thanks, but I need create dynamically the Datatable columns, that means, the json and html table must self-generate based on the columns of a sharepoint list. – Guillermo Apr 23 at 18:59
  • You can get all the field names using REST API: /_api/web/lists/getbytitle('<list title>')/fields, then loop the fields to build the data dynamically. – LZ_MSFT Apr 24 at 2:00
0

in this way I get the columns of the list and later, I store the columns in a variable and put it in the "select" of the next ajax, that way I dynamically create the datatable view

   var columnaMostrar = [];
   var objColumn;
   var columna;
   var colSel;
   function CargarListadoDeAcciones() {

    var siteUrl = _spPageContextInfo.siteAbsoluteUrl;       
    $.ajax({
        url: siteUrl + "/_api/web/lists/GetByTitle('MetadataObjetos')/Fields?$filter= TypeAsString ne 'BusinessData' and EntityPropertyName ne 'BdcIdentity'",
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function (data) {
            $("#cols").append("<th>" + "Ver Más" + "</th>");
            $.each(data.d.results, function (index, item) {
                columna = item.Title
                if (columna.includes("bdil")) {

                } else {
                    objColumn = data.d.results;

                    $("#cols").append("<th>" + columna + "</th>");


                    columnaMostrar.push(columna.replace("ñ", "_x00f1_"))


                }

                colSel = columnaMostrar.toString();

            });

            console.log("Columnas",columnaMostrar);

            cargarDT();
        },
        error: function (error) {
            alert(JSON.stringify(error));
        }
    });

}



function cargarDT() {
    var myList = [];
    var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
    var listStr = [];
    var table = $('#excelDataTable').DataTable();
    var itemID;


    $.ajax({
        url: siteUrl + "/_api/web/lists/GetByTitle('MetadataObjetos')/items?$select=BdcIdentity," + colSel,
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",

        },
        success: function (data) {

            $.each(data.d.results, function (index, item) {
                var ite = data.d.results;

                console.log(ite);
              itemID= '<a href="' + siteUrl + '/SitePages/MetadatoAtributos.aspx?Id_Objeto='+item.Id_Objeto+'">Ver</a>';
                myList = [];
                myList.push(
                        itemID
                       );
                $.each(objColumn, function (indx, itm) {
                    var colum = itm.Title;

                        var col = itm.Title;
                        var it = item[col.replace("ñ", "_x00f1_")];

                        myList.push(
                         it
                        );


                    console.log(it);

                });
                table.rows.add([

               myList


                ]).draw(false)
                $("#excelDataTable_wrapper").resize();
            });





          console.log("item", myList);


        },

        error: function (error) {
            alert(JSON.stringify(error));
        }
    });

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.