jQuery Ajax to DataTables Ajax
jQuery Ajax to DataTables Ajax
WebCodex
Posts: 71Questions: 13Answers: 3
Hi, I'm looking to convert my jQuery ajax table code to dataTables
so I can use things like reload etc
Im stuck on how I would send the variables (the POST data
) to the controller
to get the data
for the table back.
My current code:
$(document).ready(function() {
var token = '<?php echo json_encode($token); ?>';
var getUserComments = true;
var usereid = '<?php echo $_SESSION['exid']; ?>';
// Get Data from Database and Populate the DataTable
$.ajax({
url: 'controllers/recipeControl.php',
method: 'post',
dataType: 'json',
data: { getUserComments: getUserComments, usereid: usereid, token: token },
success: function(data) {
var table = $('#datatable').dataTable({
order: [[ 2, "desc" ]],
responsive: true,
data: data,
select: false,
"columnDefs": [
{ "orderable": false, "targets": 3 }
],
columns: [
{ 'data': 'recipe_comment_recipe_name',
"render": function ( data, type, row, meta ) {
if(row.batch_recipe_url === '') {
recipeLink = data;
}
else {
recipeLink = "<a href='recipe/" + row.recipe_comment_recipe_id + "'>" + data + '</a>';
}
return recipeLink;
},
},
{ 'data': 'recipe_comment',
"render": function ( data, type, row, meta ) {
return data;
},
},
{ 'data': 'recipe_comment_date',
"render": function ( data, type, row, meta ) {
if (type == "sort" || type == 'type')
return data;
// Create date from input value
var inputDate = new Date(data);
// Get today's date
var todaysDate = new Date();
//var date = (moment(data).format("ddd DD/MM/YYYY HH:mm:ss"));
// call setHours to take the time out of the comparison
if(inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0)) {
var d = new Date(data);
var hour = d.getHours();
var minute = ('0'+d.getMinutes()).slice(-2);
return 'Today ' + hour +':'+ minute;
}else {
return (moment(data).format("ddd DD/MM/YYYY HH:mm:ss"));
}
}
},
{ 'data': 'actions',
"render": function ( data, type, row, meta ) {
return "<button type='button' class='btn btn-primary recipeCommentEdit' href='#'>Edit</button><button class='btn btn-primary delete' type='button'>Delete</button>";
}
}],
});
}
})
})
This question has an accepted answers - jump to answer
This discussion has been closed.
Answers
Ok, I'm a bit closer but now I get a
TypeError: f is undefined
error,The Ajax response:
That error is found in this post:
https://datatables.net/forums/discussion/43245
Maybe you need to place
dataType: 'json',
in yourajax
option?Kevin
Fixed it.. Thanks!