0

I am working on saving the query results from mysql in an array from php and sending the array to the client in json form. All the character sets, including mysql character set, are utf8, and after checking the results after json_encode(), an invalid json string came out.

$final_result = json_encode($result, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_IGNORE | JSON_INVALID_UTF8_SUBSTITUTE);
echo $final_result; // == valid json data

After checking using the json validator, I found that a valid json data was created.

However, after the echo call, I received the data from the client to ajax and checked it, and the following error occurred, so I cannot parse it.

SyntaxError: Unexpected token  in JSON at position 64362
    at parse (<anonymous>)
    at jquery.min.js:2
    at l (jquery.min.js:2)
    at XMLHttpRequest.<anonymous> (jquery.min.js:2)

code preview image

lastime":"2020-03-19 08:55:10�����"

As a result of checking, the characters shown in the picture were created in the middle, so the parsing is not working.

$.ajax({
        url: 'test.php',
        data: {action: 'get_Data'},
        type: 'post',
        dataType: 'json'
    }).done(function (json_text) {
        alert("done");
        console.log(json_text);
        json_Obj = JSON.parse(json_text);
        console.log(json_Obj);
    }).fail(function (xhr, status, errorThrown) {
        alert("fail");
        console.log(xhr);
        console.log(xhr.responseText);
        console.log(status);
        console.log(errorThrown);
    });

Of course, I declared the data type json at the place where I called Ajax Post.

I don't know why well-encoded data in php-side is called jquery, ajax on the client side, and why the following happens.

Can you tell me what I missed?

Dharman
  • 30,962
  • 25
  • 85
  • 135
CnuCSE
  • 1
  • Is your source data of a particularly complex character set or type (like, Japanese)? If not, try the json encoding but removing `JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_IGNORE | JSON_INVALID_UTF8_SUBSTITUTE` – Martin Apr 28 '20 at 13:44
  • No, most of the data is in Korean, so if I delete JSON_UNESCAPED_UNICODE, the letters will be broken. And I deleted the rest of the options, but I couldn't solve them. – CnuCSE Apr 29 '20 at 00:02
  • It may well be worth editing your question and telling peoople that the source data is Korean, this will be important for character setting as the issue is something related to that. – Martin Apr 29 '20 at 12:53
  • Have you read [this topic](https://stackoverflow.com/questions/279170/utf-8-all-the-way-through)? – Martin Apr 29 '20 at 12:54

0 Answers0