Problems with utf8_decode in array return

1

I have a problem that has left me quite confused. I have a page in php that makes register of Ministries. In it I send the data via ajax to another php page to do the insertion, and the insertion always occurs in the normal way. Here are the codes:

Ajax sending data

  $.ajax({
    method: "POST",
    url: "ajax/insertMinisterio.php",
    data: {
      name: name,
      alternativename: alternativename,
      description: description
    },
    success: function (result){
      var returnjson = JSON.parse(result);
      var type = returnjson['type'];
      var msg = returnjson['message'];

      alert(msg);
      //reloadMinisteriosTable();
    } // Fim success
  }) // Fim ajax

});

Page that receives ajax data

<?php   
    include '../../class/autoload.php';

    $database = new Database();
    $ministerio = new Ministerio();

    $name = utf8_decode($_POST['name']);
    $alternativename = utf8_decode($_POST['alternativename']);
    $description = utf8_decode($_POST['description']);


    $ministerio->setNome($name);
    $ministerio->setNomeAlternativo($alternativename);
    $ministerio->setDescricao($description);
    $ministerio->setStatus(1);

    try{        
        $database->database_connect();

        $query = "INSERT INTO pibjm_ministerio (nome, nome_alternativo, descricao, status) VALUES ('{$ministerio->getNome()}', '{$ministerio->getNomeAlternativo()}', '{$ministerio->getDescricao()}', {$ministerio->getStatus()})";

        $result = mysqli_query($database->database_connect(), $query);

        if($result){
            $finalresult = array("query"=>$query, "type"=>"success", "message"=>"Ministério cadastrado com sucesso!");
        } else {
            $finalresult = array("query"=>$query, "type"=>"error", "message"=>"Não foi possível cadastrar o ministério! Tente novamente!");
        }

        echo json_encode($finalresult);
    }
    finally{
        $database->database_close_connection();
    }

?>

The big problem I'm having is using utf8_decode . When I use it on any of the variables, it even makes the normal insertion into the database, but always returns in ajax with the empty result . And I need utf8_decode because it leaves the right accent. If I use htmlentities, utf8_encode, or any other php function in the variables, everything works, but in ajax return the data I want , but in the database the accent is wrong. I've tested several solutions and I can not seem to get results. What is the problem that utf8_decode might be giving there in php?

    
asked by anonymous 04.09.2016 / 17:20

1 answer

1

The json_encode function only accepts values in utf8, if it has a single character in another encoding it will return null.

Apply utf8_encode to all elements of the array before passing it to json_encode.

    
04.09.2016 / 17:41