Problem with php AJAX accents PHP MYSQL using PDO

1

I can not receive the JSON from the php because the data has an accent I leave the code: PHP:

 <?php  
$pdo=new PDO("mysql:dbname=salas;host=127.0.0.1","root","");
$statement=$pdo->prepare("SELECT * FROM departamentos");
$statement->execute();
if (!$statement){
    echo 'Error al ejecutar la consulta';
}else{
    $results = $statement->fetchAll(PDO::FETCH_ASSOC);


}
echo  json_encode($results, JSON_UNESCAPED_UNICODE);
?>

Javascript code

var departamentos = [];
tablerosR();
function tablerosR() {
    tableros = [];
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var tab = JSON.parse(this.responseText);
            for (let i = 0; i < tab.length; i++) {
                departamentos.push(tab[i]);
            }
            btn_trello();
        }
    };
    xmlhttp.open("GET", "php/departamentos.php?_=" + new Date().getTime(), true);// new Date().getTime() lo usamos porque en explorer estaba cacheando la consulta y 
                                                                                //así modificamos la url consiguiendo que sea otra consulta
    xmlhttp.send();
}
    
asked by Yasiel Hernández 01.06.2018 в 11:25
source

1 answer

3

The problem of strange characters must be solved by attacking the root problem, by levels.

In this case, it would be convenient to indicate an appropriate character set when you create the connection object by doing the following:

$pdo=new PDO("mysql:dbname=salas;host=127.0.0.1;charset=UTF8","root","");

Whenever you are going to use connection objects, you should explicitly indicate that you want your data in UTF8 . This will prevent you from having problems with strange characters and invalid JSON objects due to the same problem.

That way, you can get your JSON correctly by simply doing:

echo  json_encode($results);

Thus, you solved the problem at the root, without having to resort to manipulations of the data halfway.

For more details on this you can consult this question:

answered by 04.06.2018 в 15:43