Ajax does not return text in utf-8

3

By ajax, I am querying the Database, but if the field has special characters, they appear wrong. I'm making the request in the following JS function, the result is shown in a div with the id="txtHint"

<script charset="UTF-8">
    function getProdutosSeccao(){
        var idSeccao = $('#id_seccao').val();
        if (idSeccao=="") {
            document.getElementById("txtHint").innerHTML="";
            return;
        } 
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        } else { // code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function() {
            if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET","ajax/getprodutos_seccao.php?q="+idSeccao,true);
        xmlhttp.send();
    }
</script>

In the document ajax / getprodutos_seccao.php I have the following:

<?php
$q = intval($_GET['q']);

require("ligar_ajax.php");

$sql = "SELECT * FROM tbl_produtos WHERE id_seccao = '".$q."'";
$result = mysqli_query($con,$sql);

echo '<select name="id_produto" style="width: 100%;" id="id_produto">';

while($row = mysqli_fetch_array($result)) {
    echo "<option value='".$row['id_produto']."'>".$row['nome']."</option>";
}

echo "</select>";
mysqli_close($con);
?>

It works fine, I only have the problem that the special characters appear wrong. How can I get around this?

    
asked by anonymous 16.06.2014 / 13:52

2 answers

5

Put the ajax/getprodutos_seccao.php header in the utf8 file and in your connection also change to utf8 ( mysqli_set_charset($con, "utf8") ). I've made changes to your code.

<?php
    header ('Content-type: text/html; charset=UTF-8');

    $q = intval($_GET['q']);

    require("ligar_ajax.php");

    //mudando o charset para utf8 na conexão
    mysqli_set_charset($con, "utf8")

    $sql = "SELECT * FROM tbl_produtos WHERE id_seccao = '".$q."'";
    $result = mysqli_query($con,$sql);

    echo '<select name="id_produto" style="width: 100%;" id="id_produto">';

    while($row = mysqli_fetch_array($result)) {
        echo "<option value='".$row['id_produto']."'>".$row['nome']."</option>";
    }

    echo "</select>";
    mysqli_close($con);

References:

16.06.2014 / 14:47
0

If the steps of Harry Potter do not help you have a more "on the cake" solution that is using the functions of php to convert and "unset" in utf8.

You can print the items using utf8_encode () and utf8_decode () depending on your needs.

Example:

echo "<option value='".utf8_encode($row['id_produto'])."'>".utf8_encode($row['nome'])."</option>";
    
16.06.2014 / 14:56