DataTables warning: table id = dataTable - Invalid JSON response (resolved)

2

I have the following code where I make a query.

include_once 'conexion.php';

$sql  = "SELECT * FROM herramientas";

$resultado = mysqli_query($conn, $sql);

if (!$resultado) {
    die("Error");
} else {
    while ($data = mysqli_fetch_assoc($resultado)) {
        $arreglo["data"][] = $data;
    }
    echo json_encode($arreglo);
}
mysqli_free_result($resultado);
mysqli_close($conexion);

I thought I was throwing an error by the accents but it is not like that. I throw the following error DataTables warning: table id=dataTable - Invalid JSON response . But if I make another table it works well for me. Should it be for the formats or content of the fields?

var table = $('#dataTable').DataTable({

                "destroy": true,
                "ajax": {
                    "method": "POST",
                    "url": "include/JSON.php"
                },
                "order": [
               [0, "desc"]
           ],
                "columns": [
                {
                    "data": "Codigo"
                },  {
                    "data": "Estado"
                },  {
                    "data": "Descripcion"
                }],

                "language": idioma_espanol
            });

You have already added JSON_UNESCAPED_UNICODE

Solution

$tabla = "";

if (!$resultado) {
    die("Error");
} else {

    while ($data = mysqli_fetch_assoc($resultado)) {
        // $arreglo["data"][] = $data;
        $tabla.='{"Codigo":"'.$data['Codigo'].'","Estado":"'.$data['Estado'].'"},';
    }
    $tabla= substr($tabla,0,strlen($tabla)-1);
    echo '{"data":['.$tabla.']}';
    //echo json_encode($arreglo,JSON_UNESCAPED_UNICODE);
}
mysqli_free_result($resultado);
mysqli_close($conexion);
    
asked by MoteCL 31.07.2018 в 17:02
source

1 answer

1

I do not understand very well the problem you have, if you do not want the special characters to be converted into \ u ....

The receiver has to revert the encoding, normally it does it automatically, for example in php using json_decode (data_json) it converts it without more.

But still you want them not to convert, use the JSON_UNESCAPED_UNICODE option

Test

$response = "Técnologia";

echo json_encode($response); //T\u00e9cnologia
echo json_encode($response, JSON_UNESCAPED_UNICODE); //Técnologia

You can also ensure that you do not get any strange character by doing the following:

header('Content-type: application/json; charset=utf-8');

here you have the documentation documentation

    
answered by 31.07.2018 / 18:04
source