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.
Related
i have issue on use treeTable while reload data and after save and update data form
$(document).ready(function() {
const datajson = <?php echo $data_json ?>;
$('#tablejson').treeTable({
"data": datajson,
"collapsed": true,
"responsive": true,
"lengthChange": true,
"autoWidth": false,
"fnDrawCallback": function() {
$('[data-toggle="tooltip"]').tooltip();
},
"aLengthMenu": [
[10, 50, 100, -1],
[10, 50, 100, "All"]
],
"iDisplayLength": 10,
"columns": [{
"data": "nama_module",
},
{
"data": "controller",
},
{
"data": "function",
},
{
"data": "nm_group",
},
{
"data": "label",
},
{
"data": "btn"
}
],
"order": [],
});
$('#btn-reload').click(function() {
$('#tablejson').dataTable().api().ajax.reload();
});
});
i try to click button for reload tabel use $('#tablejson').dataTable().api().ajax.reload(); but not working, this is happen while i use treeTable, if i use datatable only its work for reload or refresh table.
does anyone have the same case with me ? thanks
finally, i found a solution in my case, i use code like this
$('#btn-reload').click(function() {
$('#tablejson').DataTable()
.order([2, 'desc'])
.draw();
});
thanks....
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" }
]
});
Am fetching values from a table, its working perfectly. When the table is empty am getting aler box json formating error. How can i handle that error?
my sql query is given below, am using php zend framework
public function getProductsAction(){
$oProductModel = new Application_Model_Db_Table_Products();
$oSelect = $oProductModel->fetchAllProductItems();
echo Zend_Json::encode($this->_helper->DataTables($oSelect, array('product_id','e.ename as employee_name','name','brand','conditions','about','image_path','reserved_price','Max(b.bid_amount) as amount')));
}
and view page is
$(document).ready(function(){
jQuery('#product-table').dataTable({
<?php if(Qsm_User::isAdmin()){ ?>
"sDom": 'Tlfrtip',
"oTableTools": {
"sSwfPath": "/js/DataTables/extras/TableTools/media/swf/copy_csv_xls_pdf.swf",
"aButtons": [{
"sExtends": "collection",
"sButtonText": 'Save <span class="caret" />',
"aButtons": [ "csv", "xls", "pdf" ]
}]
},
<?php } ?>
"sPaginationType": "full_numbers",
"bProcessing": true,
"bServerSide": false,
"sAjaxSource": '/buyproduct/api/get-products',
"aoColumns": [
{"sTitle":"ID", "bVisible":false},
{"sTitle":"Emp Name", "bVisible":true},
{"sTitle":"Product", "sWidth": '10%'},
{"sTitle":"Brand", "sWidth": '10%'},
{"sTitle":"Condition", "sWidth": '10%'},
{"sTitle":"Description", "sWidth": '20%'},
{"sTitle":"Image","sWidth": '18%',
"mData": null,
"bSearchable": false,
"bSortable": false,
"fnRender": function (oObj){
var actions = "";
actions += "<span class=''>\n\
<img src='/uploads/gallery/" + oObj.aData[6] + "' alt='Image' title='Image' class='style_prevu_kit' width='0px' height='0px' />";
actions +="</span>";
return actions;
}
},
{"sTitle":"Starting Bid Price", "sWidth": '10%'},
{"sTitle":"Current Bid Price", "sWidth": '10%'},
{
"sTitle":"Bid",
"sWidth": '17%',
"mData": null,
"bSearchable": false,
"bSortable": false,
"fnRender": function (oObj){
var actions = "";
actions += "<span class='data_actions iconsweet'>\n\
<a title='Buy' href='/buyproduct/index/bid/id/" + oObj.aData[0] + "'><img src='/images/buy.png' alt='Buy' title='Buy' /></a>";
actions +="</span>";
return actions;
}
}
<?php if(Qsm_User::isAdmin()){ ?>
,{
"sTitle":"Transaction",
"sWidth": '22%',
"mData": null,
"bSearchable": false,
"bSortable": false,
"fnRender": function (oObj){
var actions1 = "";
actions1 += "<span class='data_actions iconsweet'>\n\
<a title='Transaction' href='/buyproduct/index/transaction/id/" + oObj.aData[0] + "'><img src='/images/icons/edit3.png' alt='Edit' title='Transaction' /></a>";
actions1 +="</span>";
return actions1;
}
}
<?php } ?>
]
});
});
Please anybody help me to handle this json formating error
your action will return empty string on no row condition which is invalid json data, Check the value returned from
$this->_helper->DataTables($oSelect, array('product_id','e.ename as employee_name','name','brand','conditions','about','image_path','reserved_price','Max(b.bid_amount) as amount'))
if null/or no rows echo something like this or empty row data
{
"msg": "no-data"
}
Update:
public function getProductsAction(){
$oProductModel = new Application_Model_Db_Table_Products();
$oSelect = $oProductModel->fetchAllProductItems();
if($oSelect){
echo Zend_Json::encode($this->_helper->DataTables($oSelect, array('product_id','e.ename as employee_name','name','brand','conditions','about','image_path','reserved_price','Max(b.bid_amount) as amount')));
}else{
echo '{"msg": "no-data"}'; //or edit with empty data matching required by your view
}
}
I have an web-application that uses JQuery DataTables. It uses the ajax parameter for requesting and inserting JSON data into the table.
However, at the top of the requested .php file it is checked whether the user is logged in. If this check fails it echoes a JSON notice.
<?php
session_start();
if (!isset($_SESSION['logged']) || $_SESSION['logged'] !== true) {
$array = array(utf8_encode('logged')=>utf8_encode('false'));
echo json_encode($array);
exit;
}
?>
table = $('#active-issues').DataTable({
"scrollY": pixels,
"dom": '<"top"if>rt<"bottom"><"clear">',
"paging": false,
"responsive":true,
"bProcessing": true,
"ajax": {
"data": function(){
$('#active-issues').DataTable().ajax.url(
"php/get_issues.php"
+ "?id=" + id
+ "&customer_id=" + customerid
);
}
},
columns: [
{ responsivePriority: 1 },
{ responsivePriority: 2 },
{ responsivePriority: 4 },
{ responsivePriority: 3 },
{ responsivePriority: 5 },
{ responsivePriority: 6 },
{ responsivePriority: 7 }
],
"columnDefs": [
{ "type": "alt-string", targets: 5},
{ "type": "alt-string", targets: 6},
]
});
table.ajax.reload(null, false);
Is it possible to catch the response given to JQuery DataTables? So that I can check whether result is { logged: "false" } and act accordingly?
Took a while and the help of 'allan' from datatables forums. But the problem is finally solved.
via dataSrc it's possible to manipulate the ajax result before it is printed in the table, I, however, used it to check whether the result contains logged and whether it equals to false and act accordingly if it does:
"ajax": {
"data": function(){
$('#active-issues').DataTable().ajax.url(
"php/get_issues.php?id=" + id + "&customer_id=" + customerid
);
},
"dataSrc": function ( json ) {
if(typeof json['logged'] != "undefined") {
if (json['logged'] == 'false') {
location.replace('php/logout.php');
}
}
return json.aaData;
}
},
Yes, this can be done if you do your ajax cal externally i.e perform an independent ajax request to obtain the response and the identify if the response contains
{ logged: "false" } and the populate the data to the data table accordingly.
I am using the jquery DataTables with CodeIgniter to display the data on the listing page. My query is that how can I change the class of the particulal field on basis of the condition.
I have a status field, if the status is enabled I want to add the class which shows the icon with enable status. If I disable it, then it will show the icon with disable status.
I am not able to change the class.
Here is the code.
This code is in my controller function which fetches the data.
function list_op_data() {
$this->datatables->select('om.op_id,om.is_status,om.op_name,om.op_address1,om.op_address2,cm.stCity,sm.stState,co_m.stCountryName ,om.op_pincode,om.op_contact_name,om.op_email,om.op_phone_no', false);
$this->datatables->join("country_master co_m", 'om.op_country=co_m.intCountryId');
$this->datatables->join("state_master sm", 'om.op_state=sm.intStateId');
$this->datatables->join("city_master cm", 'om.op_city=cm.intCityId');
$this->datatables->from('op_master om');
$this->datatables->where(array('om.is_deleted' => '0'));
$this->datatables->add_column('action', '<i class=" glyphicon glyphicon-ok"></i><i class="glyphicon glyphicon-pencil"></i> <i class="glyphicon glyphicon-trash"></i> ', 'op_id,is_status');
$data = $this->datatables->generate('json');
echo $data;
}
And jquery data tables code is
var tconfig = {
"processing": true,
"serverSide": true,
"ajax": {
"url": BASE_URL+"admin/op_master_details/list_op_data",
"type": "POST",
"data": "json"
},
"columnDefs": [
{
"searchable": false
}
],
"iDisplayLength": 5,
"aLengthMenu": [[5, 10, 50, -1], [5, 10, 50, "All"]],
"paginate": true,
"paging": true,
"searching": true,
"aoColumnDefs": [
{
"targets": [0],
"visible": false,
"searchable": false
},
{"bSortable": false, "aTargets": [12]},
{
"targets": [1],
"visible": false,
"searchable": false
},
]
};
var oTable = $('#operator_list_data').dataTable(tconfig);
Any help would be appreciated.
Thanks.
You need to use fnRowCallback. Add this to your initialisation code:
...
],
'fnRowCallback': function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
// Get the status form the row object
var status = aData[1];
// check the status
if(status == 'Yes'){
// add the class to the <tr>
$(nRow).addClass('glyphicon glyphicon-ok');
}
return nRow;
},
...
This will add the class glyphicon glyphicon-ok to the <tr> when status = 'Yes'. If you want to add the class to a different control, you will have to modify the addClass statement to use a different selector. e.g $(nRow).children('td')[3]).find(i).addClass()