JQuery: UTF-8 does not work with ajax request

I have a php file that uses jQuery.ajax() to capture some data from another php file in a div.

 jQuery.ajax({ type: 'POST', encoding:"UTF-8", dataType:"html", contentType: "text/plain; charset=UTF-8", url: '/path/data.php', success: function(msg) { jQuery('#dataBox').html(msg); } }); 

My problem is that if I have some "special" characters in the data that I receive through ajax, for example, Γ₯Àâ, then I get a "question mark in black diamond". If I open an external file in a browser, it will work. If I put some special characters on the main page, this works.

Some simplified codes:

data.php:

 $mysqli = new mysqli("localhost", "username", "pass", "db"); $mysqli->set_charset("utf8"); $mysqli->query("SET GLOBAL time_zone = '+00:00'"); $stmt = $mysqli -> prepare("SELECT GROUP_CONCAT(sometext) AS mytext FROM `mytable`"); $stmt -> execute(); $results = selectResults($stmt); $stmt -> close(); $mysqli -> close(); 

selectResults:

 function selectResults($stmt) { $parameters = array(); $results = array(); $meta = $stmt->result_metadata(); while ( $field = $meta->fetch_field() ) { $parameters[] = &$row[$field->name]; } call_user_func_array(array($stmt, 'bind_result'), $parameters); while ( $stmt->fetch() ) { $x = array(); foreach( $row as $key => $val ) { $x[$key] = $val; } $results[] = $x; } return $results; } 

data.php:

 foreach($results as $result){ $textArray = explode(',', $result['mytext']); } foreach($textArray as $text){ echo($text); } 
+4
source share
3 answers

Sorry, but if you get a Unicode replacement character, the input is interpreted in UTF-8, but the original input bytes do not match UTF-8, IE it was not UTF-8.

If you see the correct characters when visiting the page directly, then these should be the ajax parameters that interpret the UTF-8 interpretation for data that is actually in some other encoding, by default, Windows-1252 is used for browsers.

Send php code and / or raw data bytes.

+3
source

Fixed by setting utf8_encode() around the data that I echo() in the data.php file. I didn’t think about it, since it worked fine when opening data.php in the browser.

EDIT:

Moved utf8_encode() to the selectResults function so that it encodes all the values ​​that I get from the database.

+1
source

I will write this as an answer, as it may help others more easily.

In order to solve the problem, you should ensure that the content you output is the same as ajax expects it to be so that for utf-8 the content should be utf-8 or encoded as utf-8 using

 utf8_encode($content); 

If you can provide utf-8 content from the database, as Esailija says you won’t need to use the encode function.

+1
source

All Articles