matt.crawfoord matt.crawfoord - 5 months ago 119
jQuery Question

cannot convert Elasticsearch results to Datatables

I am trying to run functions from an elasticsearch instance through to datatables to display results.
But the problem is that I cannot display it in datatable

<script src="//cdnjs.cloudflare.com/ajax/libs/datatables/1.10.8/js/jquery.dataTables.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/datatables/1.10.8/js/dataTables.bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/datatables/1.10.8/js/dataTables.jqueryui.min.js"></script>
<script src="//cdn.datatables.net/responsive/1.0.6/js/dataTables.responsive.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/datatables/1.10.8/js/dataTables.bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/elasticsearch/10.0.1/elasticsearch.min.js"></script>


<script>
var client = elasticsearch.Client({
host: 'localhost:9200'
});

$('#example').dataTable( {
'columns': [
{ 'sTitle': 'timestamp', 'sName': 'timestamp' },
{ 'sTitle': 'message', 'sName': 'message' }
],
'bProcessing': true,
'bServerSide': true,
'fnServerData': $.fn.dataTable.elastic_datatables( {
index: 'logstash-log-*',
type: 'log',
client: client,
body: {
query: {
"bool": {
"must": [{
"term": {
"user": <?php echo $user;>
}
},
{
"range": {
"timestamp": {
"from":<?php echo $from;>,
"to":<?php echo $to;>
}
}
},
{
"query_string": {
"default_field": "_all",
"query": "*"
}
}
]}
}
}
} )
} );


Any help is appreciated.

This is the package using for jquery.elastic-datatables.js https://github.com/pidupuis/elastic-datatables

Answer

You forget to echo your php variable

<?php echo json_encode($data); ?>

plus, since you want it in json format, you have to parse it too and because of that you have to enclose your property name in double quotes.

your php variable will become:

$data = '[
    { "childName": "Child1", "childId": 1, "parentId": 1 },
    { "childName": "Child2", "childId": 2, "parentId": 2 },
    { "childName": "Child3", "childId": 3, "parentId": 1 },
    { "childName": "Child4", "childId": 4, "parentId": 2 }
]';

and dataSource will be:

dataSource: JSON.parse(<?php echo json_encode($data); ?>)

Its working :)

 Its working :)