Null value of a string variable in the JSON response object of an AJAX call

I have a jQuery AJAX call for a PHP script that retrieves a text value from a database and outputs a JSON object containing it:

	type: "GET",
	url: "my_script.php",
	success: function (jsonObj) {
		if("txt" in jsonObj) {
	error: function(jXHR, textStatus, errorThrown) {		
		console.log("The info cannot be loaded.", jXHR, textStatus, errorThrown);
	dataType: "json"

In PHP, after retrieving the text from the database, I add it to an associative array which I convert into a JSON object displayed as the response of the AJAX call:

$item['txt'] = $value; //$value is the text got from the database
header("Content-type: application/json");
echo json_encode($item);

Even though $value is not null, in the response of the AJAX call txt variable has the null value. Which means that json_encode function fails in the case of my text. As I later discovered, that is because the text I got from the database contained non-UTF-8 encoded characters and in the first parameter of the json_encode function, as PHP manual says, `All string data must be UTF-8 encoded.`
So if you want to handle non-UTF-8 encoded characters through jQuery AJAX calls with JSON data type response, you should make your own JSON encoding function. A basic example would be:

function make_json($item) {
	foreach($item as $key => $value) {
		if(is_array($value)) {
			$arr[] = '"'.$key.'":'.make_json($item[$key]);
		} else {
			$arr[] = '"'.$key.'":"'.str_replace(array("\\", "\""), array("\\\\", "\\\""), $value).'"';
	return '{'.implode(",",$arr)."}";

And the code in the PHP script goes like:

header("Content-type: application/json; charset=ISO-8859-1");
echo make_json($item);

Leave a Reply

Your email address will not be published. Required fields are marked *