I fetched data from database with passing generator_id as parameter, I executed query in Model & Controller but how to pass generator_id in jquery to fetch data into data table based on id. can anyone help me?
Example:
When passing generator id 1, in data table should be fetched generator details of id 1.
Thank you so much
My model:
public function getGeneratorRAReport($param,$generator_id){
$arOrder = array('','RA_number');
$this->db->where("RA_status",1);
$this->db->where("generator_id",$generator_id);
if ($param['start'] != 'false' and $param['length'] != 'false') {
$this->db->limit($param['length'],$param['start']);
}
$this->db->select('*,DATE_FORMAT(RA_start_date,\'%d-%m-%Y\') as RA_start_date,DATE_FORMAT(RA_end_date,\'%d-%m-%Y\') as RA_end_date');
$this->db->from('rental_agreement');
$this->db->join('customer','customer_id = customer_id_fk');
$this->db->join('generators','generator_id = generator_id_fk');
$this->db->join('rental_plan','rental_plan_id = rental_plan_id_fk');
$this->db->order_by('RA_id', 'DESC');
$query = $this->db->get();
$data['data'] = $query->result();
$data['recordsTotal'] = $this->getGeneratorRAReportTotalCount($param,$generator_id);
$data['recordsFiltered'] = $this->getGeneratorRAReportTotalCount($param,$generator_id);
return $data;
}
public function getGeneratorRAReportTotalCount($param,$generator_id){
$this->db->where("RA_status",1);
$this->db->where("generator_id",$generator_id);
if ($param['start'] != 'false' and $param['length'] != 'false') {
$this->db->limit($param['length'],$param['start']);
}
$this->db->select('*');
$this->db->from('rental_agreement');
$this->db->join('customer','customer_id = customer_id_fk');
$this->db->join('generators','generator_id = generator_id_fk');
$this->db->join('rental_plan','rental_plan_id = rental_plan_id_fk');
$this->db->order_by('RA_id', 'DESC');
$query = $this->db->get();
return $query->num_rows();
}
My controller:-
public function index()
{
$template['body'] = 'Generators/Generator_RAReport';
$template['script'] = 'Generators/Generator_RAReport_script';
$this->load->view('template', $template);
}
public function get($generator_id){
$this->load->model('Generator_model');
$param['draw'] = (isset($_REQUEST['draw']))?$_REQUEST['draw']:'';
$param['length'] =(isset($_REQUEST['length']))?$_REQUEST['length']:'10';
$param['start'] = (isset($_REQUEST['start']))?$_REQUEST['start']:'0';
$param['order'] = (isset($_REQUEST['order'][0]['column']))?$_REQUEST['order'][0]['column']:'';
$param['dir'] = (isset($_REQUEST['order'][0]['dir']))?$_REQUEST['order'][0]['dir']:'';
$param['searchValue'] =(isset($_REQUEST['search']['value']))?$_REQUEST['search']['value']:'';
$data = $this->Generator_model->getGeneratorRAReport($param,$generator_id);
$json_data = json_encode($data);
echo $json_data;
}
View :-
<div class="box-body table-responsive">
<table id="RA_details_table" class="table table-bordered table-striped">
<thead>
<tr>
<th>Sl No.</th>
<th>RA number</th>
<th>RA type</th>
<th>Customer</th>
<th>RA start date</th>
<th>RA end date</th>
<th>Description</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<!-- /.box-body -->
script :-
$(function () {
var RA_type = {'I':'Inside','O':'Outside'};
$table = $('#RA_details_table').DataTable( {
"searching": false,
"processing": true,
"serverSide": true,
"bDestroy" : true,
dom: 'lBfrtip',
buttons: [
],
"ajax": {
"url": "<?php echo base_url();?>index.php/Generator_RAReport/get/",
"type": "POST",
"data" : function (d) {
}
},
"createdRow": function ( row, data, index ) {
$table.column(0).nodes().each(function(node,index,dt){
$table.cell(node).data(index+1);
});
$('td',row).eq(2).html(RA_type[data['RA_type']]);
},
"columns": [
{ "data": "RA_id", "orderable": false },
{ "data": "RA_number", "orderable": false },
{ "data": "RA_type", "orderable": false },
{ "data": "customer_name", "orderable": false },
{ "data": "RA_start_date", "orderable": false },
{ "data": "RA_end_date", "orderable": false },
{ "data": "RA_description", "orderable": false }
]
} );
in your html area put this tag..
<input type="hidden" id="gen_id" value="<?=$gen_id?>" />
in your js code ...
var id = document.getElementById('gen_id').value;
"ajax": {
"url": "<?php echo base_url();?>index.php/Generator_RAReport/get/"+id,
"type": "GET",
"data" : function (d) {
}
},
in this case you can use both model and clientcode(jquery) in view.
code igniter dosn't force you to use mvc
$ci =& get_instance();
$ci->load->model('some-model');
$ci->some-model->get();
Related
I use laravel 8 + lumen rest api server and little bit confused because when i consume timestamp and parse it to localize format date on laravel side, also separated the display and timestamp for the js side datatables, the editColumn()it make the filtered search doesn't work because the main of search params is from the timestamp i was set before but on the view i saw it use display side, so how i can make the both filtered(search) and sort work ?
response data :
array:4 [▼
0 => array:6 [▼
"id_role" => 1
"nama_role" => "super.admin"
"created_at" => "2021-11-02T07:32:00.000000Z"
"updated_at" => "2021-11-02T07:32:00.000000Z"
"created_by" => "self"
"updated_by" => "self"
]
.. => ...
]
the column i was sorted was created_at and updated at.
RoleController.php
<?php
public function index(Request $request)
{
$raw = Http::withHeaders(['Authorization' => 'Bearer ' . Cookie::get('access_token')])->get(env('API_URL') . '/v1/kelola-role/role');
$data = $raw->json('data');
$status = $raw->json('status');
if ($request->ajax()) {
if ($status == 'success') {
return DataTables::of($data)
->addIndexColumn()
->editColumn('created_at', function ($e) {
return [
'display' => Carbon::parse($e['created_at'])->format('d/m/Y'),
'timestamp' => Carbon::parse($e['created_at'])
];
})
->editColumn('updated_at', function ($e) {
return [
'display' => Carbon::parse($e['updated_at'])->format('d/m/Y'),
'timestamp' => Carbon::parse($e['updated_at'])
];
})
->make(true);
}
return abort(401);
}
return view('pages.pengaturan.kelola-role');
}
the view :
<table class="table" id="dataRole" style="width:100%">
<thead>
<tr>
<th>No</th>
<th>Nama Role</th>
<th>Dibuat Pada</th>
<th>Diupdate Pada</th>
</tr>
</thead>
<tfoot>
<tr>
<th>No</th>
<th>Nama Role</th>
<th>Dibuat Pada</th>
<th>Diupdate Pada</th>
</tr>
</tfoot>
</table>
the js side :
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
document.addEventListener("DOMContentLoaded", function() {
$("#dataRole").DataTable({
processing: true,
serverSide: true,
ajax: {
type: "GET",
url: "",
dataSrc: function(json) {
barDone();
return json.data;
}
},
columns: [{
data: 'DT_RowIndex',
name: 'DT_RowIndex',
orderable: false,
searchable: false
},
{
data: 'nama_role',
name: 'nama_role'
},
{
name: 'created_at.timestamp',
data: {
_: 'created_at.display',
sort: 'created_at.timestamp'
}
},
{
name: 'updated_at.timestamp',
data: {
_: 'updated_at.display',
sort: 'updated_at.timestamp'
}
},
],
responsive: true,
fixedHeader: true,
select: {
style: "multi"
},
language: {
url: '{{ env('APP_URL') }}/id.json',
processing: "<div id='loadercontainer'><div class='d-flex justify-content-center text-secondary' id='loader'><div class='spinner-border' role='status'><span class='sr-only'>Loading...</span></div></div></div>"
},
dom: '<"row"<"col-12 col-sm-6 py-0"l><"col-12 col-sm-6 py-0 pt-2 pt-sm-0"fr><"col-12"t><"col-12 d-flex justify-content-between"ip>>',
render: function(data, type, row, meta) {
return meta.row + meta.settings._iDisplayStart + 1;
},
});
});
created_at sort view just work
but when i search it doesn't work
You also need to transform the search on the query level. Try using filterColumn to modify how the package will search on the edited column.
In some cases, we need to implement a custom search for a specific column. To achieve this, you can use filterColumn api.
I am stuck in that I want to reset or restart the column number from 1 after executing search in Laravel using ajax in datatable.
The code i have written so far
<table class="table table-bordered table-striped table-condensed flip-content" id="server-side-datatables">
<thead>
<tr>
<th class="dt-body-left">Serial No.</th>
<th>Document Type</th>
<th>Document Nr.</th>
<th>Date</th>
<th>Amount</th>
<th>CURENCY</th>
<th>Merchnat</th>
<th>Commnets</th>
<th width="10%">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function(){
$("#search-frm").submit(function(){
oTableCustom.draw();
return false;
});
// $("#search-frm").submit(function(e) {
// table.fnPageChange(0);
// table.fnReloadAjax();
// return false;
// });
$.fn.dataTableExt.sErrMode = 'throw';
var cur_month = '{{date("M")}}';
var title = 'WEBPAL WEB SERVICES BORDEROU CONTABILITATE LUNA:'+ cur_month;
var filename = 'WEBPAL WEB SERVICES BORDEROU CONTABILITATE LUNA:'+ cur_month;
var oTableCustom = $('#server-side-datatables').DataTable({
processing: true,
dom: 'Bfrtip',
serverSide: true,
searching: false,
ajax: {
"url": "{!! route($moduleRouteText.'.data') !!}",
"data": function ( data )
{
data.search_start_date = $("#search-frm input[name='search_start_date']").val();
data.search_end_date = $("#search-frm input[name='search_end_date']").val();
data.doc_number = $("#search-frm input[name='doc_number']").val();
data.search_parteners = $("#search-frm input[name='search_parteners']").val();
}
},
"order": [[ 0, "asc" ]],
// "fnRowCallback" : function(nRow, aData, iDisplayIndex){
// $("td:first", nRow).html(iDisplayIndex +1);
// return nRow;
// },
columns: [
{ data: 'rownum', name: 'rownum' },
{ data: 'doc_type', name: 'doc_type' },
{ data: 'doc_number', name: 'doc_number' },
{ data: 'doc_date', name: 'doc_date'},
{ data: 'amount', name: 'amount' },
{ data: 'currency', name: 'currency' },
{ data: 'partener', name: '{{ TBL_PARTENER }}.id'},
{ data: 'comments', name: 'comments' },
{ data: 'action', orderable: false, searchable: false}
],
lengthMenu: [
[ 10, 25, 50, -1 ],
[ '10 rows', '25 rows', '50 rows', 'Show all' ]
],
columnDefs: [
{ "type": "num-fmt", "targets": 4, "className": "text-left", appliesTo: 'pdf' }
],
buttons: [
{
extend: 'pageLength'
},
{
extend: 'pdfHtml5',
orientation: 'landscape',
title: title,
filename:filename,
exportOptions: {
columns: [ 0, 1, 2,3,4,5,6,7 ],
},
customize : function(doc){
doc.content[1].table.widths =
Array(doc.content[1].table.body[0].length + 1).join('*').split('');
doc.styles.tableHeader.alignment = 'left';
},
},
]
});
});
</script>
#endsection
I want output like this
just use CSS code
tbody {
counter-reset: row;
/* Set the row counter to 0 */
}
tbody tr::before {
counter-increment: row;
/* Increment the row counter*/
content: counter(row) ": ";
/* Display the row */
}
I am trying to get a dataTable on a page called "locations.php" but i am still get a JSON invalid error.
I generate the JSON dynamically using this php code on "get_SR_Locations.php":
$myjson = array();
foreach ($locationList as $list) :
$json= array(
"id" => addslashes($list['id']),
"name" => addslashes($list['name']),
"address" => addslashes($list['address']),
"telephone" => addslashes($list['telephone']),
"emailaddress" => addslashes($list['email'])
);
array_push($myjson, $json);
endforeach;
$mj=array("data"=>$myjson);
echo json_encode($mj);
The generated JSON looks something like this:
{"data":[{"id":"108","name":"Sportpark","address":"Karspstreet 501","telephone":"0123456789","emailaddress":"sport#mail.com"},{"id":"2","name":"Blaashal","address":"Gustavstreet 2920","telephone":"","emailaddress":"sporting#mailing.com"}]}
So when I put this in a JSON validator it says: VALID JSON
But I still get an invalid JSON warning by ajax.
On locations.php I have this code:
HTML
<table id="displayTable" class="table table-striped table-bordered display compact" style="width:100%">
<thead>
<tr>
<th> </th>
<th>Name</th>
<th>Address</th>
<th>Telephone</th>
</tr>
</thead>
<tfoot>
<tr>
<th> </th>
<th>Name</th>
<th>Address</th>
<th>Telephone</th>
</tr>
</tfoot>
</table>
And this JQUERY
function format ( d ) {
// `d` is the original data object for the row
return 'So Far .... NOT so Good';
}
$('#SR_sendForm').click(function(){
$('#displayTable').DataTable(
{
"order": [[ 1, "asc" ]],
"scrollY": $(window).height()-($(window).height()/10),
"scrollX": true,
"ajax": 'pages/get_SR_Locations.php?fdr='+$('#FDR').val()+'&s_term='+$('#searchterm').val()+'&city='+$('#city').val()+'&searchgroup='+$('#searchgroup').val(),
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "name" },
{ "data": "address" },
{ "data": "telephone" }
]
}
);
$('#responseTable').show();
}
});
// Add event listener for opening and closing details
$('#responseTable 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');
}
} );
And this is the error I get:
DataTables warning: table id=displayTable - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
What is wrong?
Thank you Jeff.... I did what you said ... Add json to the data instead of going via ajax.
So the solution is:
I made an tempDIV to load the data from get_SR_Locations.php
<div class="row" id="tempDIV" style="display: none"></div>
then I load the data and I use the callback for errors etc.
$('#tempDIV').load('pages/get_SR_Locations.php?fdr='+$('#FDR').val()+'&s_term='+$('#searchterm').val()+'&city='+$('#city').val()+'&searchgroup='+$('#searchgroup').val(), function(responseTxt, statusTxt, xhr) {
if(statusTxt == "success"){
$('#displayTable').DataTable(
{
"order": [[ 1, "asc" ]],
"scrollY": $(window).height()-($(window).height()/10),
"scrollX": true,
"data": JSON.parse($.trim($('#tempDIV').text())),
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "name" },
{ "data": "address" },
{ "data": "telephone" }
]
}
);
$('#responseTable').show();
}
if(statusTxt == "error"){
$('#responseTable').html("<b>Oops</b><br>Houston we have a problem");
alert("Error: " + xhr.status + ": " + xhr.statusText);
$('#responseTable').show();
}
});
And a last modification in get_SR_Locations.php:
I removed this line:
$mj=array("data"=>$myjson);
$myjson = array();
foreach ($locationList as $list) :
$json= array(
"id" => addslashes($list['id']),
"name" => addslashes($list['name']),
"address" => addslashes($list['address']),
"telephone" => addslashes($list['telephone']),
"emailaddress" => addslashes($list['email'])
);
array_push($myjson, $json);
endforeach;
echo json_encode($myjson);
I am trying to display search results into a table using DataTables. I am getting search results into JSON and validated also against valid JSON, but I get this DataTables warning:
table id=volunteer_result - Invalid JSON response.
For more information about this error, please see http://datatables.net/tn/1.
I have used below codes :
views: searchdemo.php
<div class="form-group">
<button id="search_demo" class="btn btn-form">Search</button>
</div>
<div id="demo_result_div" class="table-responsive" style="background-color:#fff;">
<table id="demo_result" class="table table-bordered table-striped">
<thead>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
</thead>
</table>
</div>
js: searchdemo.js
var table;
$('#search_demo').click(function () {
//datatables
table = $('#demo_result').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' servermside processing mode.
//"order": [], //Initial no order.
"iDisplayLength" : 10,
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('/demo/searchdemo')?>",
"type": "POST",
"dataType": "json",
"dataSrc": function (jsonData) {
return jsonData.data;
}
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ 0 ], //first column / numbering column
"orderable": false, //set not orderable
},
],
});
});
controller:Demo.php
class Demo extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('demo/Demo_model');
}
public function index() {
}
public function searchdemo() {
$data['branch_list'] = $this->Demo_model->get_company_branches();
// set form validation rules
$this->form_validation->set_rules('branch', 'Branch', 'trim|required');
// submit
if ($this->form_validation->run() == FALSE) {
// validation failed, send validation errors to the view
$data['branch_list'] = $this->Demo_model->get_company_branches();
$this->load->view('templates/header');
$this->load->view('demo/searchdemo',$data);
$this->load->view('templates/footer');
} else {
// set variables from the form
$formdata = array(
'branch_id' => $this->input->post('branch'),
'length' => intval($this->input->post('length')),
'start' => intval($this->input->post('start')),
'order' => $this->input->post('order')
);
$users_list = $this->Demo_model->get_user_details($formdata);
if(!empty($users_list )){
$data = array();
foreach ($users_list as $user) {
$row = array();
$row['name'] = $user->name;
$row['role'] = $user->role;
$data[] = $row;
}
}
}
$output = array(
"draw" => intval($this->input->post('draw')),
"recordsTotal" => $this->Demo_model->count_all_active($formdata),
"recordsFiltered" => $this->Demo_model->count_filtered($formdata),
"data" => $data
);
//output to json format
echo json_encode($output);
}
}
model:Demo_model.php
class Demo_model extends CI_Model {
var $table = "users u";
var $select_column = array("u.id", "u.name", "ur.role");
var $column_order = array(null, "u.name","ur.role");
var $order = array('u.name' => 'asc'); // default order
function make_query($formdata) {
if($formdata['branch_id']) {
$this->db->select($this->select_column);
$this->db->from($this->table);
$this->db->where('u.active','yes');
$this->db->where('u.branch_id',$formdata['branch_id']);
$this->db->join('user_role ur','u.role_id=ur.id');
}
if(isset($_POST['order'])) { // here order processing
$this->db->order_by($this->column_order[$formdata['order']['0']['column']], $formdata['order']['0']['dir']);
}
else if(isset($this->order)) {
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_user_details($formdata){
$this->make_query($formdata);
if(isset($formdata['length']) && $formdata['length'] < 1) {
$formdata['length']= '10';
} else {
$formdata['length']= $formdata['length'];
}
if(isset($formdata['start']) && $formdata['start'] > 1) {
$formdata['start']= $formdata['start'];
}
$this->db->limit($formdata['length'], $formdata['start']);
$query = $this->db->get();
return $query->result();
}
}
When I select a branch from the dropdown and click on Search button, it just returns the below JSON into the web browser instead of displaying results into search page table.
{
"draw": 0,
"recordsTotal": 2000,
"recordsFiltered": 2,
"data": [
{
"name": "Raman",
"role": "manager"
},
{
"name": "Maharaja",
"role": "admin"
}
]
}
I referred this link https://www.phpflow.com/php/server-side-datatable-sorting-searching-pagination-using-codeigniter-ii/
I have tried the many help URL for data table invalid JSON response but didn't get any luck.
You need to define data source for each column using columns.data option.
Change your initialization code as shown below:
var table = $('#demo_result').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "<?php echo site_url('/demo/searchdemo')?>",
"type": "POST"
},
"columns": [
{ "data": "name", "orderable": false },
{ "data": "role" }
]
});
I'm using Ignited Datatables to display posts in tabular way in my view. I've been struggling the last 4 days in order to do this working correct, but I can't understand what I'm doing wrong.
This is the functionality that fetches the data
// the Post_model
/**
* Get page data on datatables
*/
public function get_datatable() {
$this->load->library('datatables');
$this->datatables->select('id, title, slug, sort_description, status');
$this->datatables->from('posts');
return $this->datatables->generate();
}
// the posts controller
/**
* List all posts
*/
public function index() {
$this->data['datatables'] = true;
$this->data['data_url'] = 'admin/posts/data_ajax';
// $this->data['posts'] = $this->post_model->get_datatable();
// dump($this->data['pages']);
// load view
$this->load->view('admin/posts/index', $this->data);
}
public function data_ajax() {
$this->output->enable_profiler(false);
echo $this->post_model->get_datatable();
// echo json_encode($this->post_model->get_datatable());
exit();
}
// the view
<table class="table dataTable table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Url Slug</th>
<th>Sort Description</th>
<th>Status</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Title</th>
<th>Url Slug</th>
<th>Sort Description</th>
<th>Status</th>
</tr>
</tfoot>
<!-- <tbody>
<tr>
<td colspan="5" class="dataTables_empty"></td>
</tr>
</tbody> -->
</table>
<?php if(isset($datatables)): ?>
<?php echo js_tag('js/dataTables/jquery.dataTables.min.js'); ?>
<?php echo js_tag('js/dataTables/dataTables.bootstrap.min.js'); ?>
<script type="text/javascript">
$(document).ready(function() {
$('.dataTable').DataTable({
'bProcessing' : true,
'bServerSide' : true,
'sAjaxSource' : '<?php echo base_url($data_url); ?>',
'sServerMethod' : 'POST',
'fnServerData' : function (sSource, aoData, fnCallback) {
$.ajax({
dataType : 'json',
type : 'post',
url : sSource,
data : aoData,
success : fnCallback,
"columns": [
{ "data": "id" },
{ "data": "title" },
{ "data": "slug" },
{ "data": "sort_description" },
{ "data": "status" }
]
});
}
});
});
</script>
<?php endif; ?>
So if I access the data_ajax() function from the url like this
localhost/my-blog/admin/posts/data_ajax
and echo echo $this->page->get_datatable(); I can the records
{"draw":0,"recordsTotal":2,"recordsFiltered":2,"data":[{"id":"1","title":"First post","slug":"first-post","sort_description":"This is the first post","status":"visible"},{"id":"2","title":"Second post","slug":"second-post","sort_description":"This is the second post","status":"visible"}]}
but the problem is I can't display them on my screen. In addition I also get this warning in an alert box
DataTables warning: table id=DataTables_Table_0 - Requested unknown parameter '0' for row 0. For more information about this error, please see http://datatables.net/tn/4
This is a screenshot of what I get
How can I make this work properly? Any help would be appreciated
Please try this
Add Columns parameter to associate data with column
The code will be something like this
$('.dataTable').DataTable({
'bProcessing' : true,
'bServerSide' : true,
'sAjaxSource' : '<?php echo base_url($data_url); ?>',
'sServerMethod' : 'POST',
"columns": [
{ "data": "id" },
{ "data": "title" },
{ "data": "slug" },
{ "data": "date_published" },
{ "data": "status" }
]
'fnServerData' : function (sSource, aoData, fnCallback) {
$.ajax({
dataType : 'json',
type : 'post',
url : sSource,
data : aoData,
success : fnCallback,
});
}
});
Please refer datatables column, for details
I had similar problem. This is how I got it solved:
You have to set the columns as this
"columns": [null, null, null, null, null,{}]
Set it separately not in the Ajax.