I want to use AJAX to load data from database and display it using DataTable. The database is loaded and can be seen, but the Datatable shows:
Showing 0 to 0 of 0 entries (filtered from NaN total entries)
<table id="employee_data" class="table table-striped table-bordered">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
<td>Department</td>
<td>Job Title</td>
<td>Employee Type</td>
<td>Employee Status</td>
</tr>
</thead>
</table>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$('#employee_data').DataTable({
"processing" : true,
"serverSide" : true,
"order" : [],
"searching" : true,
"ajax" : {
url: 'employeeData.php',
type: "post",
dataType: "json",
contentType: "application/json; charset=utf-8"
},
"columns": [
{ "data": "eId"},
{ "data": "eName"},
{ "data": "eDepartment"},
{ "data": "eJobTitle"},
{ "data": "eEmployeeType"},
{ "data": "eEmployeeStatus"}
]
} );
});
</script>
employeeData.php
$query ="
SELECT *
FROM employee
ORDER BY employeeID DESC";
$result = mysqli_query($link, $query);
$data = array();
while($row=mysqli_fetch_array($result))
{
$data['data'][] = array(
'eId' => $row['employeeId'],
'eName' => $row['employeeLastName'],
'eDepartment' => $row['department'],
'eJobTitle' => $row['jobTitle'],
'eEmployeeType' => $row['employeeType'],
'eEmployeeStatus' => $row['employeeStatus']
);
}
echo json_encode($data);
Related
i am creating the simple crud system using php. when i load the to the datatable data is not loading.when i show the error on console Uncaught TypeError: Cannot read property 'length' of undefined
i am tring to solve out this problem since yesterday but i couldn't
Table
<table id="tbl-category" class="table table-responsive table-bordered" cellspacing="0"
width="100%">
<caption> Products</caption>
<thead>
<tr>
<th>Patient No</th>
<th>Name</th>
<th>Phone</th>
<th>Address</th>
</tr>
</table>
jQuery
function get_all() {
$('#tbl-category').dataTable().fnDestroy();
var oTable = $('#tbl-category').DataTable({
"ajax": {
"url": 'all_category.php',
"type": "get",
"datatype": "json"
},
"columns": [
{ "data": "patientno" },
{ "data": "name" },
{ "data": "phone" },
{ "data": "address" },
]
})
}
all_category.php Page
<?php
include("db.php");
$stmt = $conn->prepare("select patientno,name,phone,address from patient order by patientno DESC ");
if ($stmt->execute()) {
$stmt->bind_result($patientno,$name,$phone,$address);
while ( $stmt->fetch() ) {
$output[] = array ("patientno"=>$patientno, "name"=>$name,"phone"=>$phone,"address"=>$address);
}
echo json_encode( $output );
}
$stmt->close();
im getting issue to access the URL display in the display_table_content.php, to display data into my table content.
It works find if I use the php alone without the jquery and ajax.
display_table_content.php
<input type="hidden" name="job_operation" id="job_operation1" value=""/>
<div id="post_details_data" class="tb_body_container"> </div>
url:display_table_content.php?jobs_name=www
JQUERY _ AJAX
$(document).ready(function(){
fetch_user_data();
function fetch_user_data() {
var job_operation = "fetch";
$.ajax({
url:"get_table_content.php",
method:"POST",
data:{job_operation:job_operation},
success:function(data) {
$('#post_details_data').html(data);
$('#tb_jobs').DataTable({
dom: 'lBfrtip',
responsive: true,
"processing":true,
buttons:[{
extend: 'csv',
exportOptions: {columns: [0, 1, 2, 3, 4]}
},
{
extend: 'pdf',
exportOptions: {columns: [0, 1, 2, 3, 4]}
},
{
extend: 'excel',
exportOptions: {columns: [ 0, 1, 2, 3, 4]}
},
{
extend: 'print',
exportOptions: {columns: [ 0, 1, 2, 3, 4]}
}],
"order":[],
"columnDefs":[{"targets":[0, 3, 4],"orderable":false}]
});
}
});
}
});
get_table_content.php
if(isset($_POST["job_operation"])) {
require_once("database.php");
$pdo = pdo_con();
if ($_POST["job_operation"] == "fetch") {
$user_name= $_GET['jobs_name']; <-- Error seems to be from here
$fetch_data = "SELECT * FROM jobs j WHERE jobs_name = $user_name";
$result_User = $pdo->prepare($fetch_data);
$result_User->execute();
$output = '<table id="tb_jobs" class="table table-bordered table-hover table-striped table-responsive-lg" >
<thead class="thead-dark">
<tr>
<th width="60%">Job Details</th>
<th width="15%">Company Name</th>
</tr>
</thead>';
$output .= '<tbody>';
while ($row = $result_User->fetch(PDO::FETCH_ASSOC)) {
$name_text1= $row['aaa'];
$name_text2= $row['ddd'];
$output .= '
<tr>
<td>' .$name_text1. '</td>
<td>' .$name_text2. '</td>
</tr>';
}
$output .= '</tbody></table>';
echo $output;
}
}
i only the table header are being display, I cannnot fetch the table content due to the 'get' part in the get_table_content.php PHP page
If I have understood waht you want :
This line seems having no sense : $user_name= filter_input(INPUT_GET,"www",FILTER_SANITIZE_STRING); <-- Error seems to be from here
Add in display_table_content.php :
<input type="text" id="job_operation1" value=""/>
<input type="text" id="user_name" value=""/>
<script>
var jobrequest = new Object;
jobrequest.job_operation = $('#job_operation1').val();
jobrequest.user_name = $('#user_name').val();
$.ajax({
url:"get_table_content.php",
method:"POST",
data:jobrequest,
In get_table_content.php :
$job_operation = $_POST["job_operation"];
$user_name = $_POST["user_name"];
If I'm not mistaken you create a HTML table in your back end with php, and then you use DataTables to work with this table you have created, first of all DataTables can use an ajax request to get the content from a json array created in your back end, saying that I think you should do it that way since is more easy to manage for future changes, also it will let the table creation to the front end which is the best aproach, saying that I let you an example to get your table in that way:
Your Html:
<input type="hidden" name="userToFind" id="userToFind" value=""/>
<br>
<button id="btnSearch">Search Operations</button>
<br>
<div class="table-responsive" id="tableOperators" >
<h2>Table Operators</h2>
<table class="display dataTable" id="TablejobOperation" >
<thead>
<tr>
<th>Id</th>
<th>Operation</th>
<th>starts</th>
<th>ends</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Id</th>
<th>Operation</th>
<th>starts</th>
<th>ends</th>
</tr>
</tfoot>
</table>
</div>
<br>
</div>
your php:
if ($_POST["action"] == "SLC" && isset($_POST["user_name"])) {
$user_name= $_POST["user_name"];
$query = "SELECT * FROM jobs j WHERE jobs_name = $user_name";
$command= $conn->prepare($query);
$command->execute();
$result= $command->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result,JSON_UNESCAPED_UNICODE);
}
the DataTable javascript:
var jobOperation= $('#TablejobOperation').DataTable({
"destroy": true,
"responsive":{
"details": {
renderer: function ( api, rowIdx, columns ) {
var data = $.map( columns, function ( col, i ) {
return col.hidden ?
'<tr data-dt-row="'+col.rowIndex+'" data-dt-column="'+col.columnIndex+'">'+
'<td>'+col.title+':'+'</td> '+
'<td>'+col.data+'</td>'+
'</tr>' :
'';
} ).join('');
return data ?$('<table/>').append( data ) :false;
}
}
},
"autoWidth": false,
"ajax": {
"url": 'some.php',
"method": 'POST',
data:{action:"SLC", user_name:username }
},
"columns": [
{"data": "id"},
{"data": "job_operation"},
{"data": "type"},
{"data": "starts"},
{"data": "ends"}
],
"language":{"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"},
"columnDefs": [
{
"className": "dt-center", "targets": "_all"
}
]
});
Your table goes inside a click event:
$("#btnSearch").on('click',function(){
var username = $.trim($('#userToFind').val().replace(/\s+/g, ' '));
var TablejobOperation = $('#tablaSeguros').DataTable();
if ($.fn.DataTable.isDataTable("#TablejobOperation")) {
TablejobOperation.destroy();
$('#TablejobOperationtbody').remove();
}
//the datatable script from the top goes here
})
Hope it helps
I'm going straight to the point here.
what I am trying to accomplish is to populate the table using ajax.
this gives me jquery.dataTables.min.js:39 Uncaught TypeError: Cannot read property 'length' of undefined error.
here's my code:
my php code:
public function pending_data(){
$result = $this->ticketing_m->get_pending_tickets();
echo json_encode($result);
}
JQUERY
var datatable = $("#datatable");
datatable.DataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": datatable.data('url')
});
HTML
<table id="datatable" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%" data-url="<?php echo site_url(array("dashboard","pending_data")); ?>">
<thead>
<tr>
<th>Ticket Number</th>
<th>Subject</th>
<th>From</th>
<th>Date Created</th>
</tr>
</thead>
</table>
QUERY RESULT
First off, you should probably set bServerSide to false. If it is true you need to actually read the request parameters, do server side processing and structure your return data as outlined in the Server-side processing documentation. Since you are doing none of those things here I'm assuming you simply want to use Ajax sourced data and let the DataTables javascript handle the table processing
Next, structure your json with the table data inside data as shown here in example #2. Your json should look something like this:
{
"data": [
{
"date_created": "2017-06-13 13:57:24",
"full_name": "John Doe",
"subject": "Test",
"ticket_number": "Ticket 1234"
},
...
]
}
To accomplish this you might do something as simple as this in the response from pending_data():
echo json_encode(array('data' => $result));
Also, the way you have your DataTables properties set up here looks like you are either using a very old version or an outdated syntax. I'd suggest installing the latest version and using up to date code. You can get all the downloads and examples you might need at: https://datatables.net
I think your ajax source has 4 columns.
But you have 5 columns in < thead >.
Pls remove one tag in < thead >.
<table id="datatable" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%" data-url="<?php echo site_url(array("dashboard","pending_data")); ?>">
<thead>
<tr>
<th>Ticket Number</th>
<th>Subject</th>
<th>From</th>
<th>Date Created</th>
</tr>
</thead>
</table>
var oTable = $('#datatable').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "${pageContext.request.contextPath}/",
"aoColumns" : [
{ "mData": "Ticket Numbe" },
{ "mData": "Subject" },
{ "mData": "From" },
{ "mData": "Date Created" }
]
});
I don't get the exact problem.This may help..
Do something like that also use data type https://datatables.net/examples/server_side/jsonp.html
"processing": true,
"serverSide": true,
"ajax": {
"url": "scripts/jsonp.php",
"dataType": "jsonp"
}
Use it like:
var url = 'http://www.json-generator.com/api/json/get/cbEfqLwFaq?indent=2';
var table = $('#example').DataTable({
'processing': true,
'serverSide': true,
'ajax': {
type: 'POST',
'url': url,
'data': function (d) {
console.log(d.order);
return JSON.stringify( d );
}
}
});
Working Fiddle
First I'll mention what I am trying to achieve. I am using CodeIgniter framework of PHP. I have 5 tables in my database and I want to display them in Datatables format on a button click on the display page. I am using server side processing php as data source. So at first I made the code for displaying only one table in Datatable format and was successful in it. Now I want to display one table at a time out of 5 on button click event. But $aColumns length should be equal to number of columns defined in HTML table. Now considering marks tabe, it has 4 columns student_id, exam_id, subject_id and marks_achieved. Now another table is branch and has 2 columns only branch_id and branch_name. So I cannot increase or decrease tags in HTML dynamically so I am confused.
Also I am using this source to create datatables.
You can check my getTable() function here.
jQuery:
$(document).ready(function()
{
$('#datatable').dataTable({
"sPaginationType":"full_numbers",
"bJQueryUI":true,
"bProcessing": true,
"bServerSide": true,
"sServerMethod": "GET",
"sAjaxSource": "datatable/getTable",
"iDisplayStart": 0,
"iDisplayLength": 10,
"aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"aaSorting": [[0, 'asc']],
"aoColumns": [
{ "bVisible": true, "bSearchable": true, "bSortable": true },
{ "bVisible": true, "bSearchable": true, "bSortable": true },
{ "bVisible": true, "bSearchable": true, "bSortable": true },
{ "bVisible": true, "bSearchable": true, "bSortable": true }
]
})
$('input[type=button]').bind('click', function(){
var param = $(this).attr('id');
data = param + '=1';
$.ajax({
type: 'POST',
url: 'datatable',
data: data
}).done(function( data ) {
console.log(data);
$('#display_area').html(data);
});
})
});
HTML:
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="../js/javascript.js"></script>
<script type="text/javascript" src="../js/jquery.dataTables.min.js"></script>
</head>
<body id="dt_example">
<form action="" method="post">
<input type="button" id="display_branch" name="display_branch" value="Display Branch Table" >
<input type="button" id="display_marks" name="display_marks" value="Display Marks Table" >
</form>
<div id="container">
<div id="demo">
<table id="datatable" cellpadding="0" cellspacing="0" border="0" width="100%">
<thead>
<tr>
<th>Student ID</th>
<th>Exam ID</th>
<th>Subject ID</th>
<th>Marks Achieved</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
<tfoot></tfoot>
</table>
</div>
<div class="spacer"></div>
</div>
</body>
</html>
To get the columns dynamically I have made this change as shown below in datatable.php but it is not working. What is wrong here or I should try some other approach ?
if(isset($_POST['display_marks']))
{
$aColumns = array('student_id', 'exam_id', 'subject_id', 'marks_achieved');
$sTable = 'marks';
}
if(isset($_POST['display_branch']))
{
$aColumns = array('branch_id', 'branch_name');
$sTable = 'branch';
}
EDIT:
The solution posted by user1190992 works but the whole approach is changed. And in that I want to sanitize the headers of the columns. "branch_id" is displayed instead I want to display Branch ID. How can I perform this sanitization ?
This is a very simple way for creating HTML from JSON data dynamically. It doesn't use server side processing though.
JavaScript
$(document).ready(function() {
$(".abutton").click(function() {
$('#myDatatable_wrapper').detach(); //Remove existing table
var table = '<table id="myDatatable" class="table"><thead><tr>';
$.ajax({
url: 'dt.php',
data: "table_id="+$(this).attr("id"),
type: "POST",
success: function (data) {
$.each(data.aoColumns, function(key, value) {
table += "<th>"+value+"</th>";
});
table += "</tr></thead><tbody>";
$.each(data.aaData, function(key, row) {
table += "<tr>";
$.each(row, function(key, fieldValue) {
table += "<td>"+fieldValue+"</td>";
});
table += "</tr>";
});
table += '<tbody></table>';
$('.container').html(table);
$('#myDatatable').dataTable();
},
dataType: "json"
});
});
});
PHP
$table_id = filter_input(INPUT_POST, "table_id", FILTER_SANITIZE_STRING);
$dbconn = mysqli_connect("localhost", "username", "password");
if($table_id == "table1") {
$sql_query = mysqli_query($dbconn, 'SELECT * FROM display_branch');
}
else {
$sql_query = mysqli_query($dbconn, 'SELECT * FROM display_marks');
}
if(mysqli_num_rows($sql_query) == 0) {
echo "Check your ID";
exit(1);
}
$data = array();
$data['aaData'] = array();
while($row = mysqli_fetch_assoc($sql_query)) {
$data['aaData'][] = $row;
}
$data['aoColumns'] = array();
while($finfo = mysqli_fetch_field($sql_query)) {
$data['aoColumns'][] = $finfo->name;
}
echo json_encode($data);
HTML
<button id="table1" class="abutton">Table 1</button><br /><button id="table2" class="abutton">Table 2</button>
<div class="container"></div>
Hope this helps.
I am executing serverside datatables and im getting this kind of error
TypeError: c is undefined
...iRecordsDisplay=parseInt(f,10);d=0;for(e=c.length;d<e;d++)N(a,c[d]);a.aiDisplay=...
this is my server side,
require_once '../../resources/db.config.php';
$db = DATABASE::instance();
$mysqli = $db->get();
$result = $mysqli->query("SELECT * FROM mst_product");
$rows = array();
while( $r = $result->fetch_assoc() ){
$rows[] = $r ;
}
header('Content-type: application/json');
echo json_encode($rows, JSON_PRETTY_PRINT);
and my datatables
<table id="productlist" class="table">
<thead>
<tr>
<th>No</th>
<th>SKU</th>
<th>Product Description</th>
<th>Product Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
$(function () {
$("#productlist").DataTable({
"destroy": true,
"processing": true,
"serverSide": true,
"ajax": {
"url": "../../../html/data/productlist.php",
"type": "POST"
},
"columns": [
{ "data": "prod_id" },
{ "data": "prod_sku" },
{ "data": "prod_desc" },
{ "data": "prod_prc_idr" }
]
});
});
</script>
and my imports,
<!-- DATA TABLES -->
<link href="../../library/plugins/datatables/media/css/dataTables.bootstrap.min.css" rel="stylesheet" type="text/css"/>
<!-- DATATABLES -->
<script src="../../library/plugins/datatables/media/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="../../library/plugins/datatables/media/js/dataTables.bootstrap.min.js" type="text/javascript"></script>
please help me i dont know where i am doing wrong .... JSON data service is fine...