Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML is NULL in JSON object from json_encode

Tags:

json

php

utf-8

I have a ajax call calling a php file who runs a long php function which returns a JSON encoded array/object. Now I need to send HTML also into the ajax response. I thought about sending the HTML inside the array.

Is that a good practise?

Right now I cannot get it working, I get a NULL as value for that property. Don't know why.

$statHTML = '<table>';
foreach ($toHTML as $key=>$value) {
    $statHTML.= '
        <tr class="'.$key.'">
            <td class="side">'.$value[0].'</td>
            <td>'.$value[2].' '.$value[1].'</td>
        </tr>';
}
$statHTML.= '</table>';
//  echo $statHTML;   // - this works
//function return   
$answer = array('mostSearched'=>$mostSearched,
                'timeOfDay' => $timeOfDay,
                'mostSearchedDays'=>$mostSearchedDays,
                'statHTML' => $statHTML                 
            );
return json_encode($answer);

The ajax response from the console before the JSON.parse():

{
    "mostSearched": {
        "title": "Most serached houses",
        "colNames": [21],
        "rowNames": [2013],
        "rows": [1]
    },
    "timeOfDay": {
        "title": "Time of search",
        "colNames": ["07:30"],
        "rowNames": ["07:30"],
        "rows": [
            [1]
        ]
    },
    "mostSearchedDays": {
        "title": "Most searched days",
        "colNames": ["2013-12-21", "2013-12-22", "2013-12-23", "2013-12-24", "2013-12-25", "2013-12-26", "2013-12-27"],
        "rowNames": ["2013-12-21", "2013-12-22", "2013-12-23", "2013-12-24", "2013-12-25", "2013-12-26", "2013-12-27"],
        "rows": [
            [1, 1, 1, 1, 1, 1, 1]
        ]
    },
    "statHTML": null
}
like image 366
Rikard Avatar asked Jan 11 '23 15:01

Rikard


2 Answers

From php.net:

Parameters

value

The value being encoded. Can be any type except a resource.

All string data must be UTF-8 encoded.

So use:

$answer = array('mostSearched'=>$mostSearched,
        'timeOfDay' => $timeOfDay,
        'mostSearchedDays'=>$mostSearchedDays,
        'statHTML' => utf8_encode($statHTML)
);

return json_encode($answer);
like image 175
Markus Kottländer Avatar answered Jan 16 '23 20:01

Markus Kottländer


Most likely the build-in JSON parser used by PHP cannot properly parse the HTML, the easiest way to solve the issue is to base64 encode the html on the server, and then decode it on the client, using either the newer atob and btoa base64 methods, or one of the many polyfills out there.

like image 20
Entoarox Avatar answered Jan 16 '23 22:01

Entoarox