klauskpm
klauskpm

Reputation: 3145

Encode broke on PHP through Ajax with jQuery

To simplify what is happening, I'm trying to send the string "Técnico" to PHP, and it is seen as "Técnico" on $_POST var.

The error is on this project alone. I have another 3 projects running on Apache2(same /var/www folder) and they don't present this problem.

Now, the complete way the data goes.

jQuery:

$.ajax({
    url: "config/inserirCargo.php",
    type: 'POST',
    data: {
        titulo: $("#titulo").val()
    },
    success: function(data) {
        $("#cargo").html(data); 
    },
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8' // Tried with and without
});

jQuery Response:

enter image description here enter image description here

PHP:

var_dump($_POST['titulo']);
die();

My HTML already has the meta tag.

meta http-equiv="Content-Type" content="text/html; charset=utf-8"

And I've already tried these solutions alone and together:

  1. AddDefaultCharset UTF-8 - on .htaccess
  2. ini_set('charset', 'UTF-8'); - on php file
  3. header('Content-Type: text/html; charset=utf-8'); - on php file
  4. htmlentities($_POST['titulo']); - on php file
  5. titulo: encodeURIComponent($("#titulo").val()) - on js file

And I've executed "service apache2 restart" each time done some alteration to .htacces, or used ini_set.

My PHP version is 5.5.3, to be more precise:

PHP 5.5.3-1ubuntu2.6 (cli) (built: Jul 7 2014 16:54:32) Copyright (c) 1997-2013 The PHP Group Zend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies with Zend OPcache v7.0.3-dev, Copyright (c) 1999-2013, by Zend Technologies

Can someone help me?

Upvotes: 1

Views: 206

Answers (3)

klauskpm
klauskpm

Reputation: 3145

Sorry guys.

The problem was the charset of my Codeignter and the database.

It was set utf-8, but, the database is latin1.

Upvotes: 0

cram2208
cram2208

Reputation: 416

I found that if you use the following:

utf8_decode("Técnico");

it will return Técnico.

On server side, when you will collect titulo you simply have to utf8_decode it. If you need to convert all your POST vars, simply pass the $_POST array to this function.

function utf8_decode_recursive(&$data) {
    foreach ($data as &$row) {
        $row = utf8_decode($row);
    }
}

So basically I guess you cannot get a normal Técnico in UTF-8.

Upvotes: 0

manowar_manowar
manowar_manowar

Reputation: 1150

Please check php and other source files encoding. Please check table Collation.

Upvotes: 0

Related Questions