Quitar advertencia del Datatable cuando no hay datos

Quitar advertencia del Datatable cuando no hay datos

JimVCJimVC Posts: 7Questions: 0Answers: 0
edited April 2023 in Free community support

Description of problem:

Cuando hay datos carga bien sin ningún aviso, pero si la tabla está vacía me manda una advertencia y no sé cómo quitar esa advertencia o mandar dentro del tbody un mensaje como "tabla vacía"

Debugger code: Codigo para cargar la tabla

     var listar = function(){
        table=$("#tabla1").DataTable({  
            order: [[ 0, "desc" ]],
            stateSave: true,
            pageLength: 10,
            "paging": true,      
            "ordering": true,
            "info": true,
            "autoWidth": false,
            "responsive": true,
            //"destroy": true,
            "ajax":{            
                "url": "../../modelos/CategoriaModel.php", 
                "method": 'POST', // metodo POST
            },
            "columns":[
                {"data": "id_categoria"},
                {"data": "nombre"},
                {"data": "fecha"},
                {"defaultContent": `<button class="editar btn btn-success" type="button"><i class="fa-solid fa-pen-to-square"></i></button>
                                    <button type ="button" class="eliminar btn btn-danger" data-bs-toggle="modal" data-bs-target="#modalEliminar"><i class="fa-regular fa-trash-can"></i></button>`}                         
            ],
            "language": espanol
        });
        //loader
        var screen = $('#loading-screen');
        configureLoadingScreen(screen);
        // editar
        obtener_data_editar("#tabla1 tbody", table);
        //eliminar
        eliminar("#tabla1 tbody", table);}

Como hago la consulta en php

header('Content-type: text/html; charset=utf-8');
require_once '../config/config.php';
$query = "SELECT * FROM categorias where estatus= 1 ORDER BY id_categoria desc;";
$resultado=mysqli_query($conn,$query);
    while($data = mysqli_fetch_assoc($resultado)){
        //$arreglo["data"][] = array_map("utf8_encode" , $data); //POR SI HAY PROBLEMAS CON LOS CARACTERES ESPECIALES
        if (!empty($resultado)) {
                    $arreglo["data"][] =  $data;
                }else {
                    $arreglo["data"][] =  null;
                }
    }
    echo json_encode($arreglo);
    mysqli_free_result($resultado);
    mysqli_close($conn);

Error messages shown:
Lo que me muestra

Edited by Kevin: Syntax highlighting. Details on how to highlight code using markdown can be found in this guide

Replies

  • kthorngrenkthorngren Posts: 20,309Questions: 26Answers: 4,770

    Your server scrip tis responding with this error:

    Warning: Undefined variable Sarreglo in /storage/ssd2/059/20383059/public_html/CENCASI/models/CategoriaModel.php on line 16

    You will need to debug the CategoriaModel.php script to find out why the variable Sarreglo is undefined on line 16. It doesn't look like your PHP code snippet is showing this part of your code.

    Kevin

  • JimVCJimVC Posts: 7Questions: 0Answers: 0

    Gracias por responer.Si esta definida

    ya que si hay datos si envia esos datos pero cuando esta vacia sale ese mensaje o como deberia corregir para que no me muestre esa advertencia

  • kthorngrenkthorngren Posts: 20,309Questions: 26Answers: 4,770

    I'm not familiar with PHP but if the error is with json_encode($arreglo); then that suggests the while loop is not executed so the $arreglo variable doesn't exist. Maybe set a default value for the variable before the while loop, for example: $arreglo["data"][] = [];.

    Kevin

  • JimVCJimVC Posts: 7Questions: 0Answers: 0

    agregue $arreglo["data"][] = []; pero sigue sale indefinida, lo que quiero es validad que si se envia null, pues no hay datos en la BD pues que en la tabla muestre un mensaje de vacio o que ya no me salga el mensaje de advertencia.

  • kthorngrenkthorngren Posts: 20,309Questions: 26Answers: 4,770
    edited April 2023

    What exactly did you change? I meant something like this:

    $resultado=mysqli_query($conn,$query);
        $arreglo["data"][] =  [];
        while($data = mysqli_fetch_assoc($resultado)){
            //$arreglo["data"][] = array_map("utf8_encode" , $data); //POR SI HAY PROBLEMAS CON LOS CARACTERES ESPECIALES
            if (!empty($resultado)) {
                        $arreglo["data"][] =  $data;
                    }else {
                        $arreglo["data"][] =  null;
                    }
        }
        echo json_encode($arreglo);
    

    Again I'm not familiar with PHP. Maybe you need to do something differently. But if the condition of the while statement is initially false then the loop won't be entered and the variable $arreglo won't be created. You should create a value that can be used if the loop is not entered.

    Maybe someone else familiar with PHP can give you better advice.

    Kevin

  • JimVCJimVC Posts: 7Questions: 0Answers: 0

    Agregue como dijiste

    ahora ya no sale variable indefinida

    Pero ahora sale otro mensaje

    y creo que es porque la consulta que realizo: $query = "SELECT * FROM categorias where estatus= 1 ORDER BY id_categoria desc;";
    Agradesco el tiempo por responder, espero pueda ayudarme.

  • kthorngrenkthorngren Posts: 20,309Questions: 26Answers: 4,770

    The goal is to return {data: []} when there is no data. Maybe you need $arreglo["data"][] = null; instead.

    Kevin

  • JimVCJimVC Posts: 7Questions: 0Answers: 0
    edited April 2023

    lo arregle y gracias a tu ayuda

    solo tuve que agregar $arreglo["data"] = []; puede que no sea la manera recien estoy aprendiendo pero al menos funciona.

Sign In or Register to comment.