I know this must be one of the most popular questions. I can't see what's wrong with my data though. This is my php:
$sql = "SELECT eventid, event_type, date_display, date_from, date_to, location, done FROM events LIMIT 0, 30";
$get_result = mysql_query($sql);
$arr = Array();
while($res=mysql_fetch_assoc($get_result))
{
$arr['data'][] = $res;
}
echo json_encode($arr);
My JQuery:
function do_search()
{
var search_term=$("#search_term").val();
$.ajax
({
type:'post',
url:'get_results.php',
data:{
search:"search",
search_term:search_term
},
success:function(response)
{
console.log(JSON.parse(response))
$('#events').DataTable({
ajax: JSON.parse(response),
columns: [
{ data: 'eventid' },
{ data: 'event_type' },
{ data: 'date_display' },
{ data: 'date_from' },
{ data: 'date_to' },
{ data: 'location' },
{ data: 'done' },
],
"lengthMenu": [ [-1, 10, 25, 50, 100], ["All", 10, 25, 50, 100] ]
});
}
});
And my HTML:
<table id="events" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Type</th>
<th>Date</th>
<th>From</th>
<th>To</th>
<th>Location</th>
<th>To do</th>
</tr>
</thead>
</table>
This is the data I get in the console:
{
"data": [
{
"eventid": "1",
"event_type": "Senate meeting",
"date_display": "61-60",
"date_from": "61",
"date_to": "60",
"location": "Unknown",
"done": "y"
},
{
"eventid": "2",
"event_type": "Legal hearing",
"date_display": "73-70",
"date_from": "73",
"date_to": "70",
"location": "Unknown",
"done": ""
},
[etc...]
]
}
As far as I can see I'm following the data expected by DataTables. What am I missing?
I am getting seven fields for each record, and the table has seven fields indeed, also mapped in the JQuery code.
CodePudding user response:
In the example at the link you posted here: https://datatables.net/examples/ajax/objects.html, the ajax
option in the datatables config is used to provide the URL of the file/script which returns the JSON data, so that datatables can initiate an AJAX request to fetch it.
Whereas what you've done is make your own AJAX request, and then pass the response to datatables. If you're going to do that, you should provide it to datatables via the data
option instead. Your scenario, as coded now, is actually closer to this example: https://datatables.net/examples/data_sources/js_array.html
e.g.
$('#events').DataTable({
data: JSON.parse(response),
P.S. For a more complete discussion how to configure DataTables to use an AJAX request as a data source directly, see https://datatables.net/manual/ajax