dunnoman
dunnoman

Reputation: 37

jQuery HTML append causes UTF-8 national language chars issue

I encountered problems appending html that returns from UTF-8 powered InnoDB MySQL database -- object actually, that is fulfilled with data and returned to be displayed by jQuery asynchronously. The website, and database are using UTF-8 only.

So when I post something, it goes to the database, inserted, object is fulfilled with data that I inserted and appropriate html returned to jQuery, which unfortunately for some of the reason, instead of national letters, displays things like: u0142u00f3, etc.

When I refresh the website, it backs to normal, and chars are displayed properly.

Ideas?

Before it goes to the DB class:

$strNoBreakSpace = mb_convert_encoding(' ', 'UTF-8', 'HTML-ENTITIES');
$strNormalSpace = mb_convert_encoding(' ', 'UTF-8', 'HTML-ENTITIES');
$ntc = str_replace($strNoBreakSpace, $strNormalSpace, $content);

After got back from DB class:

$thread= str_replace(array(chr(10), chr(13)), '', $thread);
$thread_html = json_encode(array('status' => 1, 'success' => $thread_html));
array_push($results, $upd, $ins, $thread_html);

Before showing to jQuery:

    $list = array('success' => stripslashes($result[2]));

Is it stripslashes what ruins it? I needed to add this, and these mb_converts, else I had problem with json object within that html, having lots of slases /td, /tr\, \r\r, etc.

What jQuery sees is:

{"status":1,"success":"<tr>                    <td class="col-md-1">27.09.15</td>ttt        <td class="col-md-1 ws-nowrap"><a href="#"><span class="label label-info label-as-badge">Test</span></a></td>                    <td class="col-md-5"><a href id="id" name="id" href="#">u0142u00f3</a></td>                    <td class="col-md-5">u0142u00f3</td>                </tr>"}

Upvotes: 0

Views: 166

Answers (1)

Marcos Casagrande
Marcos Casagrande

Reputation: 40374

In PHP 5.4 You could use JSON_UNESCAPED_UNICODE flag for json_encode.

In PHP 5.3 or lower here's a helper function:

function json_encode_unicode($input) {

    return preg_replace_callback(
        '/\\\\u([0-9a-zA-Z]{4})/',
        function ($matches) {
            return mb_convert_encoding(pack('H*',$matches[1]),'UTF-8','UTF-16');
        },
        json_encode($input)
    );

}

Upvotes: 1

Related Questions