-3

I'm using ajax to get my results from my query. The ajax gives the response (sql query executes successfully) but some characters (croatian language) are broken, hence utf-8 doesn't function correctly.

In my php script, I've tried the following:

$con->set_charset('utf8');

OR

$con->query("SET NAMES 'utf8'");

I've also added the following line in the header:

header('Content-Type: text/html; charset=utf-8');

as well as the content type in my client-ajax code:

contentType: "application/json; charset=utf-8"

Still my characters break, I'm not getting utf-8 valid response. In phpMyAdmin I've got the utf8_general_ci collation which I believe is ok.

EugenSunic
  • 13,162
  • 13
  • 64
  • 86

1 Answers1

2

I have found the answer.

The second argument (JSON_UNESCAPED_UNICODE) inside the json_encode() function was the problem.

echo json_encode($myArray,JSON_UNESCAPED_UNICODE);

So along with JSON_UNESCAPED_UNICODE you have to add the following line of code which is ENOUGH.

$con->set_charset('utf8');

If you switched $con->set_charset('utf8'); to $con->query("SET NAMES 'utf8'"); then it wouldn't work (you'd get a server 500 error).

The header('Content-Type: text/html; charset=utf-8'); is not required.

Before you fix your php code you have to make sure that when you run your query against the database in phyMyAdmin or smillar, the collation needs to be utf8 in my case utf8_general_ci.

Of-course, don't forget the

dataType: "json"

in jquery-ajax.

EugenSunic
  • 13,162
  • 13
  • 64
  • 86
  • 1
    It would have helped if you'd have defined what "broken" means exactly... http://stackoverflow.com/q/22745662/476 – deceze Apr 22 '16 at 11:41
  • I missed to write the json_encode function, therefore I assume I didn't get the right response... – EugenSunic Apr 22 '16 at 12:15
  • 1
    You ultimately missed to describe your problem. You described what you did, you did at no point say what exactly was "wrong". Turns out, nothing was "wrong" at all... – deceze Apr 22 '16 at 12:59