user6065185 user6065185 - 4 days ago 9
jQuery Question

Cannot show jquery datables with php json_encode?

i try to get curl data to jquery data table (like this https://datatables.net/examples/api/row_details.html),

Here is the response.php

echo json_encode($results);


the json_encode output:

{
"hittotal":69511,
"data":[
{
"....."
},.....
]
}




HTML table and javascript in my web page(datatables.php):

<script>
function format ( d ) {
// `d` is the original data object for the row
return '<table cellpadding="3" cellspacing="0" border="0" style="padding-left:50px;">'+
'<tr>'+
'<td>message:</td>'+
'<td>'+(d.message)+'</td>'+
'</tr>'+
'<tr>'+
'<td>id:</td>'+
'<td>'+d.id+'</td>'+
'</tr>'+

'</table>';
}

$(document).ready(function() {
var table = $('#example').DataTable( {

"ajax": {
'type': 'POST',
'url': 'response.php',
'data': {
from: '<? echo $from; ?>',
to: '<? echo $to; ?>'

},
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "datetime" },
{ "data": "message" },

],
"order": [[1, 'asc']]
} );

// Add event listener for opening and closing details
$('#example tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );

if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
} );
} );
</script>


html :



<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th>datetime</th>
<th>message</th>

</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th>datetime</th>
<th>message</th>

</tr>
</tfoot>
</table>



i am sure echo json_encode($results) is not empty but why cannot shown in data tables ?

Answer

You may want to take a look at the child functionality in datatables: https://datatables.net/examples/api/row_details.html

Instead of having the extra information you see in the example you could put table rows instead.

Comments