Trying to Load JSON on DataTable

Trying to Load JSON on DataTable

kayro2222kayro2222 Posts: 4Questions: 1Answers: 0

Hi!

I'm trying to use a JSON to load datatable rows, but the datatable always return me a error, that is: DataTables warning: table id=dt_basic - Requested unknown parameter 'id' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4

I get this JSON from the InitComplete function from another datatable e save the result on sessionStorage. Like this:

"initComplete": function (settings, json) {
sessionStorage.setItem('json', json);
}

The JSON returns me:

[{"id":"36566","nomeFantasia":"LOJAO DOS ALUMINIOS","titulo":"Ajuda para gerar e corrigir arquivo do Sped Fiscal","codigoPrograma":"9220","nome":"ALANO","status":"Aberto","dataAbertura":"11-12-2017 00:00","motivo":"Comercial"}]

my columns configuration is:

"aoColumns": [
{"data": "id"},
{"data": "nomeFantasia"},
{"data": "titulo"},
{"data": "codigoPrograma"},
{"data": "nome"},
{"data": "status"},
{"data": "dataAbertura"},
{"data": "motivo"},
{"data": function (data) {
if (data.status == 'Fechado') {
return '<a style="width: 100%" class="btn btn-primary btn-sm" title="Trâmite" id="editChamado" href="#ajax/chamados-edit.php?id=' + data.id + '&st=0"><i class="fa fa-edit"></i></a>'
} else {
return '<a style="width: 45%" class="btn btn-primary btn-xs" title="Trâmite" id="editChamado" href="#ajax/chamados-edit.php?id=' + data.id + '&st=1"><i class="fa fa-edit"></i></a><a style="margin-left: 5%; width: 45%;" title="Fechar" id="deleteChamado" href="#ajax/chamados-delete.php?id=' + data.id + '&acao=delete" class="btn btn-success btn-xs"><i class="fa fa-check"></i></a>';

                            }
                        }
                    }
                ]

my table:

Chamado Nome Fantasia Título Codigo Rotina Atendente Status Data Abertura Motivo Ação

Please, anyone send me a ligth!
Thank you!

Answers

  • kthorngrenkthorngren Posts: 20,581Questions: 26Answers: 4,823

    Not clear on what you are doing with initComplete. Are you using ajax to get the data?

    If so then you probably will need to use ajax.dataSrc to change the source of your data from the default of data. Try setting it to "dataSrc": "" like the second example in the doc.

    Kevin

  • allanallan Posts: 62,241Questions: 1Answers: 10,210 Site admin

    Yes, could you show the entire DataTables initialisation rather than just part of it please?

    Thanks,
    Allan

  • kayro2222kayro2222 Posts: 4Questions: 1Answers: 0

    Hi guys! Thanks for the reply!

    I will try to explain my objective with the code.

    I have two datatables, one in a button click event and another on $(document).ready event.

    The user will set parameters for the search on the click event datatable. They will leave the page for edit informations of the row(s) that he search and will return to the page with the datatable. In this moment, i have to show the rows that he search previously.

    So, when the user clicks on the search button, i have to save the JSON, to load on the datatable the initialize on ready event and i use sessionStorage to do that, on initComplete function of the datatable.

    My datatable click event:

    var dados = {
    "numChamado": $("#numChamado").val(),
    "cliente": $("#nomeFantasia").val(),
    "atendente": $("#atendente").val(),
    "ativo": $("#ativo").val(),
    "motivo": $("#motivo").val(),
    "modulo": $("#modulo").val(),
    "tipoAcesso": <?php echo $_SESSION['tipoAcesso']; ?>,
    "idUsuario": <?php echo $_SESSION['idUsuario']; ?>,
    "idCliente": <?php echo $_SESSION['idCliente']; ?>,
    "dataInicio": $("#dataInicio").val(),
    "dataFim": $("#dataFim").val(),
    "acao": "buscar"
    };

                var url = 'ajax/controller/ajax/chamados_controller.php';
    
                var table = $('#dt_basic').DataTable({
                    destroy: true,
                    "aoColumns": [
                        {"data": "id"},
                        {"data": "nomeFantasia"},
                        {"data": "titulo"},
                        {"data": "codigoPrograma"},
                        {"data": "nome"},
                        {"data": "status"},
                        {"data": "dataAbertura"},
                        {"data": "motivo"},
                        {"data": function (data) {
                                if (data.status == 'Fechado') {
                                    return '<a style="width: 100%" class="btn btn-primary btn-sm" title="Trâmite" id="editChamado" href="#ajax/chamados-edit.php?id=' + data.id + '&st=0"><i class="fa fa-edit"></i></a>'
                                } else {
                                    return '<a style="width: 45%" class="btn btn-primary btn-xs" title="Trâmite" id="editChamado" href="#ajax/chamados-edit.php?id=' + data.id + '&st=1"><i class="fa fa-edit"></i></a><a style="margin-left: 5%; width: 45%;" title="Fechar" id="deleteChamado" href="#ajax/chamados-delete.php?id=' + data.id + '&acao=delete" class="btn btn-success btn-xs"><i class="fa fa-check"></i></a>';
    
                                }
                            }
                        }
                    ],
                    "ajax": {
                        url: url,
                        data: dados,
                        type: "post",
                        dataType: "json",
                        dataSrc: ''
                    },
                    "oLanguage": {
                        "sLengthMenu": "Mostrar _MENU_ registros por página",
                        "sZeroRecords": "Nenhum registro encontrado",
                        "sInfo": "Mostrando de _START_ à _END_ de _TOTAL_ registro(s)",
                        "sInfoEmpty": "Mostrando 0 de 0 registros",
                        "sInfoFiltered": "(filtrado de _MAX_ registros)",
                        "sSearch": "Pesquisar: ",
                        "oPaginate": {
                            "sFirst": "Início",
                            "sPrevious": "Anterior",
                            "sNext": "Próximo",
                            "sLast": "Último"
                        }
                    },
                    "order": [0, "desc"],
                    "sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-12 hidden-xs'l>r>" +
                            "t" +
                            "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                    "autoWidth": true,
                    "preDrawCallback": function () {
                        if (!responsiveHelper_dt_basic) {
                            responsiveHelper_dt_basic = new ResponsiveDatatablesHelper($('#dt_basic'), breakpointDefinition);
                        }
                    },
                    "rowCallback": function (nRow) {
                        responsiveHelper_dt_basic.createExpandIcon(nRow);
                    },
                    "drawCallback": function (oSettings) {
                        $("#dt_basic tbody #deleteChamado").hover(function () {
                            $("#dt_basic tbody tr td #deleteChamado").tooltip();
                        });
                        $("#dt_basic tbody #editChamado").hover(function () {
                            $("#dt_basic tbody tr td #editChamado").tooltip();
                        });
                        responsiveHelper_dt_basic.respond();
                        //responsiveHelper_dt_basic = null;
                    },
                    "initComplete": function (settings, json) {
                        responsiveHelper_dt_basic = null;
                        sessionStorage.setItem('json', json);
                    }
                });
    

    My $(document).ready event datatable:

    var table = $('#dt_basic').DataTable({
    destroy: true,
    "aoColumns": [
    {"data": "id"},
    {"data": "nomeFantasia"},
    {"data": "titulo"},
    {"data": "codigoPrograma"},
    {"data": "nome"},
    {"data": "status"},
    {"data": "dataAbertura"},
    {"data": "motivo"},
    {"data": function (data) {
    return '<a style="width: 45%" class="btn btn-primary btn-xs" title="Trâmite" id="editChamado" href="#ajax/chamados-edit.php?id=' + data.id + '&st=1"><i class="fa fa-edit"></i></a><a style="margin-left: 5%; width: 45%" title="Fechar" id="deleteChamado" href="#ajax/chamados-delete.php?id=' + data.id + '&acao=delete" class="btn btn-success btn-xs"><i class="fa fa-check"></i></a>';
    }
    }
    ],
    "data": sessionStorage.getItem('json'),
    "dataType": "json",
    "oLanguage": {
    "sLengthMenu": "Mostrar MENU registros por página",
    "sZeroRecords": "Nenhum registro encontrado",
    "sInfo": "Mostrando de START à END de TOTAL registro(s)",
    "sInfoEmpty": "Mostrando 0 de 0 registros",
    "sInfoFiltered": "(filtrado de MAX registros)",
    "sSearch": "Pesquisar: ",
    "oPaginate": {
    "sFirst": "Início",
    "sPrevious": "Anterior",
    "sNext": "Próximo",
    "sLast": "Último"
    }
    },
    "order": [0, "desc"],
    "sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-12 hidden-xs'l>r>" +
    "t" +
    "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
    "autoWidth": true,
    "preDrawCallback": function () {
    if (!responsiveHelper_dt_basic) {
    responsiveHelper_dt_basic = new ResponsiveDatatablesHelper($('#dt_basic'), breakpointDefinition);
    }
    },
    "rowCallback": function (nRow) {
    responsiveHelper_dt_basic.createExpandIcon(nRow);
    },
    "drawCallback": function (oSettings) {
    $("#dt_basic tbody #deleteChamado").hover(function () {
    $("#dt_basic tbody tr td #deleteChamado").tooltip();
    });
    $("#dt_basic tbody #editChamado").hover(function () {
    $("#dt_basic tbody tr td #editChamado").tooltip();
    });
    responsiveHelper_dt_basic.respond();
    //responsiveHelper_dt_basic = null;
    },
    "initComplete": function (settings, json) {
    responsiveHelper_dt_basic = null;

                    }
                });
    

    So, i have to load the JSON data from the search button o ready event.

    Is that clear for you guys?

    Thanks a lot!

  • kayro2222kayro2222 Posts: 4Questions: 1Answers: 0

    note: the datatable on the click event button works fine.

  • kayro2222kayro2222 Posts: 4Questions: 1Answers: 0

    Hi guys!

    I was able to figured out the problem. I just used JSON.stringify on the JSON in the initComplete function of the click event datatable. When the page loads, the trigger the ready function datatable, i used JSON.parse and it works.

    My JSON needed to be like this:

    codigoPrograma
    :
    "9220"
    dataAbertura
    :
    "11-12-2017 00:00"
    id
    :
    "36566"
    motivo
    :
    "Comercial"
    nome
    :
    "ALANO"
    nomeFantasia
    :
    "LOJAO DOS ALUMINIOS"
    status
    :
    "Aberto"
    titulo
    :
    "Ajuda para gerar e corrigir arquivo do Sped Fiscal"

    Thanks a lot for you time!
    Merry christmas and a happy new year!

  • allanallan Posts: 62,241Questions: 1Answers: 10,210 Site admin

    Good to hear you've got it working - thanks for posting back.

    One quick thing - if you just need to save the search that was applied to the DataTable, you could use stateSave to do that.

    Allan

This discussion has been closed.