Problem with UTF-8 when receiving Ajax data

Asked

Viewed 265 times

0

Good morning, I checked other reports of the same problem, but I could not use any of the answers given in them... I tried some but it doesn’t solve.

I am using datatables to show/insert/edit data from a form, everything is working EXCEPT the accent part. He shows it as "£" What happens in mine is this, I have the page index.html in it the accent is normal, but the data received by ajax is bugged.

I’ve already inserted UTF8 in everything that is place and does not solve, I checked and I’m already doing the data gathering, but it’s not working, it could be wrong. I’m a layman with ajax, I’m using as a butthole, but I’ve made it this far =)

Jquery usage because of datatables, it has a charset in ajax Settings

    ajaxSettings: {
    url: ajaxLocation,
    type: "GET",
    isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
    global: true,
    processData: true,
    async: true,
    contentType: "application/x-www-form-urlencoded; charset=UTF-8",

In the login part I also put

<?php
header ('Content-type: text/html; charset=utf-8');
    $server = "localhost";
    $user = "root";
    $password = "**";//
    $bd = "**";

    $conexion = mysqli_connect($server, $user, $password, $bd);
    if (!$conexion){ 
        die('Error de Conexión: ' . mysqli_connect_errno());    
    }   
?>

my index.html to vary tbm is with utf-8

<!DOCTYPE html>
<html lang="pt_BR">
<head>
   <meta charset="utf-8"/>
    <title>*</title>

What happens is this, in my index.html I have textboxes that when saved, they call the save.php function

var guardar = function(){
    $("form").on("submit", function(e){
        e.preventDefault();
        var frm = $(this).serialize();
        $.ajax({
            method: "POST",
            url: "guardar.php",
            data: frm
        }).done( function( info ){
        console.log( info );        
            var json_info = JSON.parse( info );
            mostrar_mensaje( json_info );
            limpiar_datos();
            listar();
        });
    });
}

that redirects to the save.php page ( full page of how to use).

<?php

    include ("conexion.php");

    $idusuario = $_POST["idusuario"];
    $dia = $_POST["dia"];
    $nombre = $_POST["nombre"];
    $apellidos = $_POST["apellidos"];
    $dni = $_POST["dni"];
    $ca = $_POST["ca"];
    $pot = $_POST["pot"];
    $pon = $_POST["pon"];
    $bairro = $_POST["bairro"];
    $predio = $_POST["predio"];
    $tecnico = $_POST["tecnico"];
    $entre = $_POST["entre"];
    $motivo = $_POST["motivo"];
    $estado = $_POST["estado"];
    $opcion = $_POST["opcion"];
    $informacion = [];  

    switch ($opcion) {
        case 'registrar':
                if( $dia != "" &&  $nombre != "" && $apellidos != "" && $dni != "" && $ca != "" && $pot != "" && $pon != "" && $bairro != "" && $predio != "" && $predio != "" && $tecnico != "" &&  $entre != "" && $motivo != "" && $estado != ""  ){
                    $existe = existe_usuario($dni, $conexion);
                    if( $existe > 100000 ){ 
                        $informacion["respuesta"] = "EXISTE";
                        echo json_encode($informacion);
                    }else{ 
                        registrar($dia, $nombre, $apellidos, $dni, $ca, $pot, $pon, $bairro, $predio, $tecnico,  $entre, $motivo, $estado, $conexion);
                    }               
                }else{
                    $informacion["respuesta"] = "VAZIO";
                    echo json_encode($informacion);
                }
            break;
        case'modificar':
            modificar($dia, $nombre, $apellidos, $dni, $ca, $pot, $pon, $bairro, $predio, $tecnico, $entre, $motivo, $estado, $idusuario, $conexion);
            break;
        case'eliminiar':
            eliminar($idusuario, $conexion);
            break;
        default:
            $informacion["respuesta"] = "OPCION_VACIA";
            echo json_encode($informacion);
            break;  
    }

        function existe_usuario($dni, $conexion){
        $query = "SELECT idusuario FROM curriculo WHERE dni = '$dni';";
        $resultado = mysqli_query($conexion, $query);
        $existe_usuario = mysqli_num_rows( $resultado );
        return $existe_usuario;
    }

    function registrar($dia, $nombre, $apellidos, $dni, $ca, $pot, $pon, $bairro, $predio, $tecnico, $entre, $motivo, $estado, $conexion){
        $query = "INSERT INTO curriculo VALUES(0, '$dia', '$nombre', '$apellidos', '$dni', '$ca', '$pot', '$pon', '$bairro', '$predio', '$tecnico',  '$entre', '$motivo', '$estado');";
        $resultado = mysqli_query($conexion, $query);       
        verificar_resultado($resultado);
        cerrar($conexion);
    }


    function modificar($dia, $nombre, $apellidos, $dni, $ca, $pot, $pon, $bairro, $predio, $tecnico, $entre, $motivo, $estado, $idusuario, $conexion){ 
    $query= "UPDATE curriculo SET nombre='$nombre', 
    apellidos='$apellidos', 
    dni='$dni',
    ca='$ca',
    pot='$pot',
    pon='$pon',
    bairro='$bairro',
    predio='$predio',
    tecnico='$tecnico',
    dia='$dia',
    entre='$entre',
    motivo='$motivo',
    estado='$estado'
    WHERE idusuario=$idusuario";

    $resultado = mysqli_query($conexion, $query);
    verificar_resultado( $resultado );
    cerrar( $conexion );
    }

    function eliminar($idusuario, $conexion){
    $query= "UPDATE curriculo SET estado= 0
    WHERE idusuario=$idusuario";
    $resultado = mysqli_query($conexion, $query);
    verificar_resultado( $resultado );
    cerrar( $conexion );
    }

    function verificar_resultado ( $resultado ) { 
        if ( !$resultado )  $informacion["respuesta"] = "ERROR";
        else    $informacion["respuesta"] = "BIEN";
        echo json_encode ( $informacion );
     }

    function cerrar ( $conexion ) { 
        mysqli_close ( $conexion );
}

?>  

As I informed you, EVERYTHING works EXCEPT the accentuation, when you write it is for example

In my MYSQL you are also saved with£. but if I enter the phpmyadmin and edit the field for just ã, it is normal. So the difficulty really is in ajax.

I hope you can help me, don’t necessarily need to help me in the right way, or more complicated... Can be solved with gambiarras, ( since it works xD) And/or just forcing not to add the "£" character after the accented letter.

I’ve tried almost everything I know and I couldn’t figure it out... The more I look, the more I get lost :(

I have tried using JSON_UNESCAPED_UNICODE within my json_encode. Then the error code changes from "£" to "ã"

  • Do not add "Solved" to the title. I know it’s common practice in many forums, but here the operation is different: just add an answer below (in the "Your Answer" field), and then accepted the answer

  • Vale remembers that the files .html, .js and .php must also be saved as UTF8 otherwise nothing helps..

  • Oops, sorry I didn’t know that, so it was solved =)

No answers

Browser other questions tagged

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