Problem for popular Datatable?

Asked

Viewed 2,963 times

0

I can’t find the error, simply do not populate the table:

ERROR

Datatables Warning: table id=Tabevolucao - Invalid JSON Response. For more information about this error, Please see http://datatables.net/tn/1

AJAX

$('#TabEvolucao').DataTable({
    "processing" : true,        
    "ajax" : {
        "type" : "POST",
        "url" : "estrutura/tabevolucao.php",
        dataSrc : '',
        "data" : function(d){d.idcliente = 127;}
    },
    "columns" : [   {"data" : "id"}, 
                    {"data" : "data"}, 
                    {"data" : "descricao"},
                    {"data" : "nome"},
                    {"data" : "ativo"}
                ],      
    "aaSorting": [[1,'asc']],
     "iDisplayLength": 7,
     "bFilter": true,
     "aaSorting": [[1,'asc']],              
    "language": {               
        "sEmptyTable": "Nenhum registro encontrado",
        "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
        "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
        "sInfoFiltered": "(Filtrados de _MAX_ registros)",
        "sInfoPostFix": "",
        "sInfoThousands": ".",
        "sLengthMenu": "_MENU_ resultados por página ",
        "sLoadingRecords": "Carregando...",
        "sProcessing": "Processando...",
        "sZeroRecords": "Nenhum registro encontrado",
        "sSearch": "Pesquisar",
        "oPaginate": {
            "sNext": "Próximo",
            "sPrevious": "Anterior",
            "sFirst": "Primeiro",
            "sLast": "Último"
            },
        "oAria": {
            "sSortAscending": ": Ordenar colunas de forma ascendente",
            "sSortDescending": ": Ordenar colunas de forma descendente"
            }
        }   

});

PHP

    <?php include("../includes/config.php");

if ($_POST)
{
    $id = (int) $_POST['idcliente'];

    if ($_POST['acao'] == 'select' && is_int($id))
    {
        $select = "select E.id,E.data,E.descricao,U.nome,E.ativo FROM evolucao as E ";
        $select .= "inner join usuarios as U on (U.id=E.id_usuario) WHERE E.id = ".$id;
        $rs = $con->prepare($select);           
        if($rs->execute())
        {
            if($rs->rowCount() > 0)
            {
                $data = array();
                while($row = $rs->fetch(PDO::FETCH_OBJ))
                {
                    $data[] = array('success' => '1',
                                    'id' => $row->id,
                                    'data' => $row->data,
                                    'descricao' => $row->descricao,
                                    'nome' => $row->nome,
                                    'ativo' => $row->ativo,
                                    'msg' => 'Tudo certo!'
                                );
                }
            }
        }
    }
}
else
{
    $data = array('success' => '0', 'msg' => 'Ocorreu um erro, não achamos nada!');
}    
echo json_encode($data);    

ERROR

DataTables warning: table id=TabEvolucao - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1

3 answers

0


You have problems returning your code, in the variable $data is not returning a array only the last item:

<?php include("../includes/config.php");

if ($_POST)
{
    $id = (int) $_POST['idcliente'];

    if ($_POST['acao'] == 'select' && is_int($id))
    {
        $select = "select E.id,E.data,E.descricao,U.nome,E.ativo FROM evolucao as E ";
        $select .= "inner join usuarios as U on (U.id=E.id_usuario) WHERE E.id = ".$id;
        $rs = $con->prepare($select);           
        if($rs->execute())
        {
            if($rs->rowCount() > 0)
            {
                $data = array();
                while($row = $rs->fetch(PDO::FETCH_OBJ))
                {
                    $data[] = array('success' => '1',
                                    'id' => $row->id,
                                    'data' => $row->data,
                                    'descricao' => $row->descricao,
                                    'nome' => $row->nome,
                                    'ativo' => $row->ativo,
                                    'msg' => 'Tudo certo!'
                                );
                }
            }
        }
    }
}
else
{
    $data = array('success' => '0', 'msg' => 'Ocorreu um erro, não achamos nada!');
}    
echo json_encode($data);    

basically the last line echo json_encode($data); have to return a array in the following structure:

[
    {
        "success":'1',
        "id": 1,
        "data": "1999-01-01", ...
    },
    {
        "success":'1',
        "id": 2,
        "data": "1999-01-05", ...
    }
]

so that the Datatables can load the data, a gold problem also found is in the javascript where you reformat the die, needlessly and also the die should come ready from the PHP, then remove that function from dataSrc that in the PHP the data has been sent correctly:

$('#TabEvolucao').DataTable({
        "processing" : true,        
        "ajax" : {
            "type" : "POST",
            "url" : "data.php",
            dataSrc : ''
        },
        "columns" : [   {"data" : "id"}, 
                        {"data" : "data"}, 
                        {"data" : "descricao"},
                        {"data" : "nome"},
                        {"data" : "ativo"}
                    ],      
        "aaSorting": [[1,'asc']],
         "iDisplayLength": 7,
         "bFilter": true,
         "aaSorting": [[1,'asc']],              
        "language": {               
            "sEmptyTable": "Nenhum registro encontrado",
            "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
            "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
            "sInfoFiltered": "(Filtrados de _MAX_ registros)",
            "sInfoPostFix": "",
            "sInfoThousands": ".",
            "sLengthMenu": "_MENU_ resultados por página ",
            "sLoadingRecords": "Carregando...",
            "sProcessing": "Processando...",
            "sZeroRecords": "Nenhum registro encontrado",
            "sSearch": "Pesquisar",
            "oPaginate": {
                "sNext": "Próximo",
                "sPrevious": "Anterior",
                "sFirst": "Primeiro",
                "sLast": "Último"
                },
            "oAria": {
                "sSortAscending": ": Ordenar colunas de forma ascendente",
                "sSortDescending": ": Ordenar colunas de forma descendente"
                }
            }   

    });

I have in mind that often are silly mistakes, so I will propose yet a minimum example with a fixed data without ajax so you have an idea of how it works:

$('#TabEvolucao').DataTable({
  "processing": true,
  "data": [{"id":1,"descricao":"Tiger Nixon","position":"System Architect","salary":"$320,800","data":"2011\/04\/25","nome":"Edinburgh","extn":"5421","ativo":1},{"id":2,"descricao":"Nixon","position":"Architect","salary":"$450,800","data":"2012\/12\/3","nome":"Edinburgh Peter","extn":"0151","ativo":0}],
  "columns": [{
      "data": "id"
    },
    {
      "data": "data"
    },
    {
      "data": "descricao"
    },
    {
      "data": "nome"
    },
    {
      "data": "ativo"
    }
  ],
  "aaSorting": [
    [1, 'asc']
  ],
  "iDisplayLength": 7,
  "bFilter": true,
  "aaSorting": [
    [1, 'asc']
  ],
  "language": {
    "sEmptyTable": "Nenhum registro encontrado",
    "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
    "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
    "sInfoFiltered": "(Filtrados de _MAX_ registros)",
    "sInfoPostFix": "",
    "sInfoThousands": ".",
    "sLengthMenu": "_MENU_ resultados por página ",
    "sLoadingRecords": "Carregando...",
    "sProcessing": "Processando...",
    "sZeroRecords": "Nenhum registro encontrado",
    "sSearch": "Pesquisar",
    "oPaginate": {
      "sNext": "Próximo",
      "sPrevious": "Anterior",
      "sFirst": "Primeiro",
      "sLast": "Último"
    },
    "oAria": {
      "sSortAscending": ": Ordenar colunas de forma ascendente",
      "sSortDescending": ": Ordenar colunas de forma descendente"
    }
  }

});
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>

<table id="TabEvolucao"></table>

As described in documentation to pass some additional filter material in the server side is:

$(document).ready(function() {
    $('#example').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "scripts/server_processing.php",
            "data": function ( d ) {
                d.myKey = "myValue";
                // d.custom = $('#myInput').val();
                // etc
            }
        }
    } );
} );

in its specific case in the part of ajax:

$('#TabEvolucao').DataTable({
        "processing" : true,        
        "ajax" : {
            "type" : "POST",
            "url" : "data.php",
            "dataSrc" : "",
            "data" : function(d){
                 d.idcliente = 1; // aqui passe o número desejado.
             }
        },
  • Thanks @Virgilio Novic for the help, but there is still a problem, note that I need to pass a parameter to php, already tried but even this rolling. I have a fnc that searches this id "var idcliente = buscarcliente();",

  • @Jeffersonmeireles missed a glance at the documentation on the link: https://datatables.net/examples/server_side/custom_vars.html and made an edition to illustrate!

  • not this one, I’ve tried to use the documentation, but something I’m doing wrong. does not bring record, even adding a fixed value in the parameter, I made an edit

  • @Jeffersonmeireles if you edited did not pay attention to the code I put, and other thing often the problem can not be reproduced, is a local problem.

  • 1

    You’re right, I found the problem, it was my lack of attention.

  • more help on this table, now I want to get the value of one of the table row fields, I need to open a modal passing this value.

  • @Jeffersonmeireles if: https://datatables.net/extensions/responsive/examples/display-types/bootstrap-modal.html you need to open another question, each question and its answers, simply open another question and enter the correct context for it!

Show 2 more comments

0

No need to add field post rather create .js for editing the fields id - colula. The current model DataTable You don’t have to discriminate against every field. For each type of programming there is a code. If it is PHP you don’t need all that command. format the data, no need and also the data should come ready from the PHP, then remove that function from dataSrc that in the PHP the data has been sent correctly:

$('#TabEvolucao').DataTable({
        "processing" : true,        
        "ajax" : {
            "type" : "POST",
            "url" : "data.php",
            dataSrc : ''
        },
        "columns" : [   {"data" : "id"}, 
                        {"data" : "data"}, 
                        {"data" : "descricao"},
                        {"data" : "nome"},
                        {"data" : "ativo"}
                    ],      
        "aaSorting": [[1,'asc']],
         "iDisplayLength": 7,
         "bFilter": true,
         "aaSorting": [[1,'asc']],              
        "language": {               
            "sEmptyTable": "Nenhum registro encontrado",
            "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
            "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
            "sInfoFiltered": "(Filtrados de _MAX_ registros)",
            "sInfoPostFix": "",
            "sInfoThousands": ".",
            "sLengthMenu": "_MENU_ resultados por página ",
            "sLoadingRecords": "Carregando...",
            "sProcessing": "Processando...",
            "sZeroRecords": "Nenhum registro encontrado",
            "sSearch": "Pesquisar",
            "oPaginate": {
                "sNext": "Próximo",
                "sPrevious": "Anterior",
                "sFirst": "Primeiro",
                "sLast": "Último"
                },
            "oAria": {
                "sSortAscending": ": Ordenar colunas de forma ascendente",
                "sSortDescending": ": Ordenar colunas de forma descendente"
                }
            }   
        });

I have in mind that often are silly mistakes, so I will propose yet a minimum example with a fixed datum without ajax so you have an idea of how it works:

$('#TabEvolucao').DataTable({
  "processing": true,
  "data": [{"id":1,"descricao":"Tiger Nixon","position":"System Architect","salary":"$320,800","data":"2011\/04\/25","nome":"Edinburgh","extn":"5421","ativo":1},{"id":2,"descricao":"Nixon","position":"Architect","salary":"$450,800","data":"2012\/12\/3","nome":"Edinburgh Peter","extn":"0151","ativo":0}],
  "columns": [{
      "data": "id"
    },
    {
      "data": "data"
    },
    {
      "data": "descricao"
    },
    {
      "data": "nome"
    },
    {
      "data": "ativo"
    }
  ],
  "aaSorting": [
    [1, 'asc']
  ],
  "iDisplayLength": 7,
  "bFilter": true,
  "aaSorting": [
    [1, 'asc']
  ],
  "language": {
    "sEmptyTable": "Nenhum registro encontrado",
    "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
    "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
    "sInfoFiltered": "(Filtrados de _MAX_ registros)",
    "sInfoPostFix": "",
    "sInfoThousands": ".",
    "sLengthMenu": "_MENU_ resultados por página ",
    "sLoadingRecords": "Carregando...",
    "sProcessing": "Processando...",
    "sZeroRecords": "Nenhum registro encontrado",
    "sSearch": "Pesquisar",
    "oPaginate": {
      "sNext": "Próximo",
      "sPrevious": "Anterior",
      "sFirst": "Primeiro",
      "sLast": "Último"
    },
    "oAria": {
      "sSortAscending": ": Ordenar colunas de forma ascendente",
      "sSortDescending": ": Ordenar colunas de forma descendente"
    }
  }
});

-1

Partner the error is not in datatable Yes in the programming inserted in each column. Pulling fields by database is different than pulling by standard text mode.

Is trying to implant in php, crud, codeigniter, laravel or another. Pdo, python?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.