In my applications I often use AJAX calls to get certain variables along with html code, sampe JSON:
{
'result': '1',
'error': '0',
'someVar': 'abc',
'outputHTML': '<table>....</table>',
}
to create such JSON I have to assign each value in the associative array and encode it (server side: PHP code).
$response=array(
'result' => 1,
'error' => 0,
'someVar' => 'abc',
'outputHTML' => '<table>....</table>',
);
echo @json_encode($response);
die();
I have my HTML code directly inside my classes, but I would like to move it into a separate template file to reduce class size and separate class code from html code. The problem is that I'm unable to get template code into a variable, sample:
function ajax_response()
{
$response=array();
//of course below code doesn't work
$response['outputHTML']=include('table-html.php');
echo @json_encode($response);
die();
}
where table-html.php file includes:
<table>
...
</table>
One solution to the problem is to use output buffering to catch the content of table-html.php file and insert it into the variable. The downside is that the output buffering isn't always enabled on servers, so on some hostings such code wouldn't work correctly. Do you have any suggestions on alternative solutions to the problem ?
Note: Template files use PHP code to generate dynamically the HTML code, so the included PHP file must be parsed.
UPDATE
In fact this code will work:
$response['outputHTML']=include('table-html.php');
if the table-html.php has the following content:
<?php
$output = '<table>'.$some_var.'</table>';
return $output;