datatables using codeigniter does not add result to table - php

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" }
]
});

Related

Server-side processing with ajax source data

I tried to submit dynamic data to jscript and render the data using php from api url, but how can I pass the pagination number to the datable jscript and letting php to define the pageindex dynamically?
I tried to pass the value into the function, it will totally reload the ajax table for me and stay back at page number 1 instead of page number 2.
the api returns:
{
"data": [...],
"pageindex": 1,
"totalrecord": 708,
"totalpage": 71
}
My Form jquery:
$('.form-filter form').on('submit', function(e) {
e.preventDefault();
const start = $('.form-filter [name=start]').val();
const end = $('.form-filter [name=end]').val();
const type = $('.form-filter [name=type]').val();
const status = $('.form-filter [name=status]').val();
if (this.checkValidity() !== false) {
action_handle('fire_search');
var datetime = timezone(start, end);
paymentTable(datetime[0], datetime[1], type, status);
}
});
The datatable jscript:
function paymentTable(from, to, type, status) {
const paymentTable = $('#table').DataTable({
ajax: {
type : "POST",
url: "/api/somethinng/history",
data: {"start": from, "end": to, "type": type, "status": status},
dataSrc: function(json) {
if(json == "no data") {
return [];
} else {
return json.data;
}
}
},
responsive: {
details: {
renderer: $.fn.dataTable.Responsive.renderer.tableAll({
tableClass: 'ui display nowrap table-sm table-bordered'
})
}
},
processing: true,
serverSide: true,
deferRender: true,
destroy: true,
order: [[0,"desc"]],
}
});
paymentTable.draw();
}
My PHP function to get the data from api:
public function api_history() {
$raw = $this->balance_model->data_source([
'type' => 1,
'status' => 1,
'fromdate' => '2020-10-01',
'todate'=> '2020-10-05',
'pageindex' => 1,
'rowperpage' => 1000
]);
if( $raw['code'] == 1 && $raw['data'] != [] ):
asort($raw['data']);
$data = [];
foreach( $raw['data'] as $ph ):
$row = [];
$row[] = $ph['date'];
$row[] = $ph['id'];
$row[] = $ph['amount'];
$data[] = $row;
endforeach;
echo json_encode([
'data' => $data
'draw' => (int)$_POST['draw'],
'recordsTotal' => $raw['totalRecord'],
'recordsFiltered' => $raw['totalRecord']
]);
else:
echo json_encode(['no data']);
endif;
}

how to pass json data into datatable with passing id in codeigniter?

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();

how can I read my id row from datatables jquery in php / codeigniter?

I want to get the row id to after sent it to php code,but im using datatables jquery plugin , however I show my id into datables , but datatables is generating td instead of inputs. if it were it will be easy to read it in php, but how can I read my row id of datable in php... I tried $_POST, but I cant because I havent any name on tds. other thing im using codeigniter. once I can read my id row I can use it for where id = id to update my item.
table
var table = $('#example').DataTable({
"lengthChange": false,
responsive: true,
dom: 'Blfrtip',
buttons: [{
extend: 'excelHtml5',
exportOptions:{
columns: [1,2,3,4,5,6]
}
},{
extend: 'csvHtml5',
exportOptions:{
columns: [1,2,3,4,5,6]
}
},{
extend: 'pdf',
exportOptions: {
columns: [1,2,3,4,5,6]
}
}],
ajax: {
url: URL_GET_DATATABLE,
type: 'POST',
},
columnDefs:[{
targets: -1,
data: null,
defaultContent: "<a href='#'><span class='glyphicon glyphicon-pencil'></span></a>"
},{
targets: 6,
render: function (data) {
return (data == 1) ? "<span class='label label-success'>active</span>":"<span class='label label-danger'>inactive</span>";
}
}],
fnRowCallback: function (data,nRow) {
if (nRow[6] == 0) {
$(data).css({'background-color':'#f2dede'});
}else if(nRow[6] == 1){
$(data).css({'background-color':'#dff0d8'});
}else{
}
}
});
model
public function datatable(){
$this->db->select('id,descripcion,precio_compra,precio_venta,precio_mayoreo,existencia_minima,existencia,storelte_articulos.status');
$this->db->from('storelte_articulos');
$query = $this->db->get();
return $query->result_array();
}
controller
public function datatable(){
$array = $this->products->datatable();
$this->json($array);
$data = array();
foreach ($array as $rows){
array_push($data, array(
$rows['id'],
$rows['descripcion'],
$rows['precio_compra'],
$rows['precio_venta'],
$rows['precio_mayoreo'],
$rows['existencia'],
$rows['status']
));
}
$this->json(array('data' => $data));
}
update controller
public function updateProduct($data){
$this->db->update('storelte_articulos',$data);
$this->db->where('id');
}
You need to put your ID into an input, but set it as hidden. That way the data isn't being shown to the end user, but it is available through post data.
As it is able to be seen with developer tools / inspect I would suggest encoding it for display then decoding it for use with the database queries.

DataTables error logging out user on 302 response

I've got two problems with a Laravel based site that I'm attempting to upgrade.
It's using DataTables for a lot of reports that I really don't want to have to rewrite but from time to time I'm getting 302 (found) responses instead of JSON.
This leads to problem two: when this happens, the user gets logged out.
Does anyone have any suggestions what could cause these issues?
Using:
Laravel 4.1.27
jQuery 1.8.3
PHP 5.5.19
DataTables 1.10.0
One of the DataTables calls:
function makeMiscItemsTable(tableSelector, url) {
if (url === undefined) {
miscItemsTable = $(tableSelector).DataTable({
"fnRowCallback": function (nRow, aData, iDisplayIndex) {
$(nRow).children('.donation-id').html(['<a title="View/Edit" href="/inventory/donation/details/', aData['donation_id'], '">', aData['donation_id'], '</a>'].join(""));
// Apply stying to rows based on the item's status: received, recycled or sent/other
if (aData['status'] == 'sent') {
$(nRow).addClass('row-blue');
} else if (aData['status'] == 'recycled') {
$(nRow).addClass('row-red');
} else {
$(nRow).addClass('row-green');
}
},
"oLanguage": {
"sProcessing": "<img src='/assets/images/ajax_clock_small.gif'>",
"sSearch": ""
},
"bDeferRender": true,
"bProcessing": true,
"sAjaxSource": '/inventory/donation/misc_items',
"sPaginationType": "four_button",
"bRetrieve": true,
"aaSorting": [[1, "desc"]],
'aLengthMenu': [[10, 25, 50, 100, -1], [10, 25, 50, 100, 'All']],
'iDisplayLength': 25,
'aoColumns': [
{
"mDataProp": null,
"sClass": "center-text",
"sDefaultContent": '<input type="checkbox" name="misc-item-select" class="misc-item-check" value="selected" false>'
},
{
"mDataProp": 'donation_id',
"sClass": 'donation-id'
},
{"mDataProp": 'description'},
{
"mDataProp": 'status',
"sClass": "hide"
},
{
"mDataProp": 'id',
"sClass": "hide misc-item-id"
}
],
"aoColumnDefs": [
{'bSortable': false,
'aTargets': [0]
}
]
});
} else {
miscItemsTable.ajax.url(url).load();
}
}
The controller code:
public function get_misc_items($status = null)
{
$attributes = DonatedMiscItem::$datatable_attributes;
if ($status === null) {
$items = DonatedMiscItem::all($attributes);
} else {
$items = DonatedMiscItem::where('status', $status)->get($attributes);
}
$results = array();
$count = $items->count();
foreach ($items as $item) {
$results[] = $item['original'];
}
return Response::json(array('aaData' => $results, 'iTotalRecords' => $count, 'iTotalDisplayRecords' => $count));
}
The route:
Route::get('donation/misc_items/{status?}', 'DonationController#get_misc_items');
The URL called:
site.com/inventory/donation/misc_items?_=1425080932188
The 302 respose is a redirect, and is probably triggered from an application session timeout, that's why the users gets logged out at the same time. Check the location header to find if the actual url of the redirect is a login page.

how to get and pass multiple checkboxes value to server side (php) through controller using angularjs

how to get and pass multiple checkboxes values to server side (php) through controller using angularjs.
but it didn't throw any console error or else.
i don't know what's wrong with my code.
<label ng-repeat="role in roles">
<input type="checkbox" checklist-model="user.roles" checklist-value="role" ng-change="checkFirst()"> {{role}}
</label>
$scope.roles = [
'guest',
'user',
'customer',
'admin'
];
$scope.user = {
roles: ['user']
};
$scope.checkFirst = function() {
$scope.user.roles.splice(0, $scope.user.roles.length);
$scope.user.roles.push('guest');
console.log($scope.user.roles);
};
Since your new to Angular, let me post some example that might help you.
<div ng-app="checkbox" ng-controller="homeCtrl">
<div ng-repeat="item in list">
<input type="checkbox" checkbox-group />
<label>{{item.value}}</label>
</div>{{array}}
<br>{{update()}}
var app = angular.module('checkbox', []);
app.controller('homeCtrl', function($scope) {
$scope.array = [1, 5];
$scope.array_ = angular.copy($scope.array);
$scope.list = [{
"id": 1,
"value": "apple",
}, {
"id": 3,
"value": "orange",
}, {
"id": 5,
"value": "pear"
}];
$scope.update = function() {
if ($scope.array.toString() !== $scope.array_.toString()) {
return "Changed";
} else {
return "Not Changed";
}
};
})
.directive("checkboxGroup", function() {
return {
restrict: "A",
link: function(scope, elem, attrs) {
// Determine initial checked boxes
if (scope.array.indexOf(scope.item.id) !== -1) {
elem[0].checked = true;
}
// Update array on click
elem.bind('click', function() {
var index = scope.array.indexOf(scope.item.id);
// Add if checked
if (elem[0].checked) {
if (index === -1) scope.array.push(scope.item.id);
}
// Remove if unchecked
else {
if (index !== -1) scope.array.splice(index, 1);
}
// Sort and update DOM display
scope.$apply(scope.array.sort(function(a, b) {
return a - b
}));
});
}
}
});
Let me know if this help for you.

Categories