how to bind datatable columns dymanicall from ajax post in jquery

how to bind datatable columns dymanicall from ajax post in jquery

SriRishithaSriRishitha Posts: 42Questions: 4Answers: 0

$.ajax({
type: 'POST',
url: someurl
success: function (resp) {
if (resp.length > 0) {
var headers = [];
// VAR obj = $.parseJSON(resp);
// var response = JSON.parse("'resp+"'");
debugger
$.each(resp, function (index, value) {
debugger
var keys = [];
$.each(Object.keys(value), function (index1, value1) {

                      var locdatatype = "";
                      if (index == 0) {
                          //headers[index] = value1;
                          keys.push(value1);
                          debugger
                          //if (columns.length > 0)
                          //    $.each(columns, function (i, item) {

                          //        if (item.AliasName == "[" + value1 + "]") {

                          //            locdatatype = item.DataType;

                          //            colname = item.ColName;
                          //        }

                          //    });
                      }
                  });

var table = $('#viewtbl').DataTable({
// responsive: true,
//ServerSide: true,
//autoWidth: false,
// dom: 'Bfrtip',
columns: keys,
data:resp,
scrollX: false,
orientation: 'landscape',
pageSize: 'LEGAL',
Paginate: true,
dataType: "json"});

i got the error like this
Cannot use 'in' operator to search for '8' in Active1

Answers

  • SriRishithaSriRishitha Posts: 42Questions: 4Answers: 0

    i got the answer

  • bwilli33bwilli33 Posts: 6Questions: 0Answers: 0

    What was the answer I am currently fighting this as well?

  • kthorngrenkthorngren Posts: 21,468Questions: 26Answers: 4,977

    Here is an example of building the columns based on the keys of the first data object:
    http://live.datatables.net/fafuyeyu/55/edit

    Of course you can have your server script generate the column names and store them in another object within the JSON response.

    Kevin

  • bwilli33bwilli33 Posts: 6Questions: 0Answers: 0

    I have the server passing the column names now as another object but i can't seem to get the datatables to read them in. I want to replace columns with the json object columns so its more dynamic

    so instead of

    "columns": [ { "data": "id" },
    { "data": "category" }
    ],

    it would be

    "columns" : "data.columns"

    here is a sample of my script

    var BuyerTable = $('#BuyerCategories').DataTable({
    dom: 'Bfrtipl',
    select: true,
    buttons: [
    'colvis',
    {
    extend: 'selected',
    text: '<i class="fas fa-eye"></i><span class="d-none d-lg-inline"> View Selected</span>',

            action: function (e, dt, node, config) {
                var rows = dt.rows({ selected: true }).count();
                if (rows !== 0) {
                    var myValue = dt.rows({ selected: true }).data()[0].id;
                    window.location = '/BuyerCategories/Details/' + myValue;
                }
            },
            className: "btn btn-info"
        },
        {
            extend: 'selected',
            text: '<i class="fas fa-trash"></i><span class="d-none d-lg-inline"> Delete Selected</span>',
    
            action: function (e, dt, node, config) {
                var rows = dt.rows({ selected: true }).count();
                if (rows !== 0) {
                    var myValue = dt.rows({ selected: true }).data()[0].id;
                    window.location = '/BuyerCategories/Delete/' + myValue;
                }
            },
            className: "btn btn-danger"
        },
        {
            text: '<i class="fas fa-plus"></i><span class="d-none d-lg-inline"> Add Category</span>',
            action: function (e, dt, node, config) {
                window.location = '/BuyerCategories/Create';
            },
            className: "btn btn-success"
        }
    ],
    "order": [[1, "asc"]],
    "processing": true,
    "serverSide": true,
    "paging": true,
    "ordering": true,
    "ajax": {
        url: "/Categories/getBuyerCategories",
        type: 'POST'
    
    
    },
    "columns": [ { "data": "id" },
        { "data": "category" }
    ],
    "columnDefs": [
        {
            "targets": [0],
            "searchable": false
    
        },
        {
            "targets": [],
            "visible": false
        }
    ],
    "responsive": true
    

    });

  • kthorngrenkthorngren Posts: 21,468Questions: 26Answers: 4,977

    You can do what you want. But the data.columns objects need to match what Datatables is looking for. Like the data object and possibly the title object if you want to define the column headers. Either your server script needs to use the correct structure or you need to fix it in your Javascript code.

    Kevin

  • bwilli33bwilli33 Posts: 6Questions: 0Answers: 0
    edited March 2018

    I think that is my trouble i don't know what datatables is looking for i have tried a combination of things and none of it seems to want to work. i have to type out the column names instead of it just doing all of them automatically.

    I tried with the example you linked out too but for whatever reason kept getting a 500 error on the ajax call. which ironically is the same one as the one in the datatables.

  • kthorngrenkthorngren Posts: 21,468Questions: 26Answers: 4,977

    Not sure about the 500 error. Your server logs will indicate the problem. It looks like you are doing a POST request in Datatables. Did you do the same with the external ajax call?

    In your Datatables init code you are passing an array of objects to the columns option. In your example you have:

    "columns": [ { "data": "id" },
    { "data": "category" }
    ],
    

    Your script needs to build the same array of objects for data.columns.

    Also you will need to manually assign the data option instead of using ajax in your Datatables init code, for example:
    "data": data.data,

    This snippet shows an example of assigning the columns object to the data.columns variable. Also shows using the data to populate your data instead of using ajax:

    var data.columns =  [ { "data": "id" },
    { "data": "category" }
    ];
    
    var BuyerTable = $('#BuyerCategories').DataTable({
      "columns" : data.columns,   //no quotes around data.columns 
      "data": data.data,
      .......  //remaining init code
    });
    

    Kevin

  • bwilli33bwilli33 Posts: 6Questions: 0Answers: 0

    i've tried the following but still no luck keep getting requested unknown parameter 0 for row 0 column 0

    "paging": true,
        "ordering": true,
        "ajax": {
            url: "/Categories/getBuyerCategories",
            type: 'POST',
            dataSrc: function (json) {
                console.log(json);
                $.each(json.columns, function (key, value) {
                    columns.push({
                        data: value.toLowerCase(),
                        title: value.toLowerCase()
                    });
    
                });
                console.log(columns);
                return json.data;
            }
    
    
        },
        "columns" : columns,
        //"columns": [ { "data": "id" },
        //    { "data": "category" }
        //],
        "columnDefs": [
            {
    
  • bwilli33bwilli33 Posts: 6Questions: 0Answers: 0

    and thank you so much for helping!

  • kthorngrenkthorngren Posts: 21,468Questions: 26Answers: 4,977

    I think the problem is with the async processing of the ajax call. My guess is that Datatables is processing the columns option before the ajax response thus the columns are built. You may also see an error in the browsers console.

    Since you are using server side processing you do need to leave your ajax config in the Datatables init code. However I think you will need to use one before the Datatables init code to just get the columns and process them like you are now. This is still and async process so you will need a callback function like my example or put all you DT config in the success function of the columns ajax call.

    You can easily test this by setting the columns variable to what you want before your Datatables init code and run your code as is.

    Hope this makes sense.

    Kevin

This discussion has been closed.