How to get json data after redraw of datatable? - json

When page load for the first time, I got json object returned from controller. But after deletion of a data it doesn't return json object. I mean, I can access requestTable.ajax.json() after initial load of var requestTable = $('#Request-Table').DataTable({});. But after any event when the table got redrawn, requestTable.ajax.json() gives an error.
My main concern is how to get value of recordsTotal from json object after every event. Can anyone assist me with that?
Routes:
Route::group(['prefix' => '/requests'], function () {
Route::get('/show', [
'uses' => 'InvitationController#show',
'as' => 'requests.show',
]);
Route::delete('/delete/{id}', [
'uses' => 'InvitationController#destroy',
'as' => 'requests.destroy',
]);
});
Controller:
public function show()
{
return Datatables::of(Invitation::query()->whereNull('invitation_token'))->make(true);
}
public function destroy($id)
{
$invitations = Invitation::where('id', $id)->delete();
return Response::json($invitations);
}
DataTable Function:
// Initial Load
requestTable = $('#Request-Table').DataTable({
processing: true,
serverSide: true,
order: [[ 3, "asc" ]],
pagingType: "full_numbers",
ajax: '{{ route('requests.show') }}',
columns: [
{ data: 'id', name: 'id' },
{ data: 'email', name: 'email' },
{ data: 'created_at', name: 'created_at' },
],
columnDefs: [
{
targets: 0,
visible: false,
searchable: false
},
{
targets: 3,
render: function(data, type, row, meta){
return "<button type=\"button\" class=\"delete-request btn btn-sm btn-danger\" data-toggle=\"modal\" data-target=\"#Modal-Request-Delete\" data-id=\""+row.id+"\">Delete Request</button>";
},
searchable: false,
orderable: false
}
]
});
});
// Delete Request
$('body').on('click', '#Btn-Delete-Request', function () {
var requestId = $("#Delete-Request").data("id");
$("#Delete-Request").prop('id', '');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "delete",
url: "/requests/delete/"+requestId,
success: function (data) {
window.requestTable = $('#Request-Table').dataTable();
window.requestTable.fnDraw();
},
error: function (data) {
console.log('Error:', data);
}
});
});

Don't need to send data from delete you can just refresh your table by ajax.reload() function
below i put your code with modify check it's working or not
// Initial Load
var requestTable ;
requestTable = $('#Request-Table').DataTable({
processing: true,
serverSide: true,
order: [[ 3, "asc" ]],
pagingType: "full_numbers",
ajax: '{{ route('requests.show') }}',
columns: [
{ data: 'id', name: 'id' },
{ data: 'email', name: 'email' },
{ data: 'created_at', name: 'created_at' },
],
columnDefs: [
{
targets: 0,
visible: false,
searchable: false
},
{
targets: 3,
render: function(data, type, row, meta){
return "<button type=\"button\" class=\"delete-request btn btn-sm btn-danger\" data-toggle=\"modal\" data-target=\"#Modal-Request-Delete\" data-id=\""+row.id+"\">Delete Request</button>";
},
searchable: false,
orderable: false
}
]
});
});
// Delete Request
$('body').on('click', '#Btn-Delete-Request', function () {
var requestId = $("#Delete-Request").data("id");
$("#Delete-Request").prop('id', '');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "delete",
url: "/requests/delete/"+requestId,
success: function (data) {
requestTable.ajax.reload();
},
error: function (data) {
console.log('Error:', data);
}
});
});
above var requestTable so in delete function you can access that and requestTable.ajax.reload(); this function you can use to refresh you table

Related

Laravel Yajra Datatable Duplicating Data When page number change

Laravel Yajra DataTable Duplicating Data when changing the page number.
page 01 data response
page 02 data response
Some data will appear on all pages (duplicate) ..for example, id 513.
if ($request->ajax()) {
$data = Lead::with('getSource', 'getPreferredProject', 'tasks')
->where('is_verified', 1)
->whereNull('attended_by')
->whereNull('leads_maker_status')
->where(function ($q) {
$q->where('lead_stage_id','!=',6)->orWhereNull('lead_stage_id');
})
->orderBy('verified_at', 'DESC');
return DataTables::of($data)
->addIndexColumn()
->editColumn('lead_date', function ($data) {
return $data->lead_date != '0000-00-00' ?date('d-m-Y', strtotime($data->lead_date)) : '';
})
->editColumn('verified_at', function ($data) {
return $data->verified_at != '0000-00-00' ? date('d-m-Y', strtotime($data->verified_at)) : '';
})
->rawColumns(['lead_date','verified_at'])
->make(true);
}
Request Function
function getLeadsMakerData() {
$('#leadsMakerTable').DataTable({
processing: true,
serverSide: true,
pageLength: 10,
paging: true,
responsive: true,
scrollX: false,
ajax: {
url: "{{ route('leads-maker.index') }}",
},
columns: [
{
data: 'DT_RowIndex',
name: 'DT_RowIndex',
orderable: false,
searchable: false
},
{
data: 'enquirer_name',
name: 'enquirer_name'
},
{
data: 'lead_date',
name: 'lead_date'
},
{
data: 'verified_at',
name: 'verified_at'
},
{
data: 'mobile',
name: 'mobile'
},
{
data: 'email',
name: 'email'
},
{
data: 'source',
name: 'source'
},
{
data: 'preferred_project',
name: 'preferred_project'
},
{
data: 'action',
name: 'action',
searchable: false,
orderable: false,
},
],
"drawCallback": function (settings) {
$('.dropdown-trigger').dropdown();
},
lengthMenu: [5, 10, 25, 50, 75, 100]
});
}
this is the source code I am using to send the request
and I am calling this method inside $( document ).ready().

Export buttons in meteor

Template.users.rendered = function () {
Template.instance().subscribe('userList');
if (Session.get('apply_tablestyling')==1) {
console.log('in datatable');
$('#users').dataTable({
"paging": true,
"lengthChange": false,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": false
});
}
}
I am using datatables-bootstrap-3, I need to add export buttons. Everything is working except showing the export buttons.
have you tried adding buttons to your initialization?
buttons: ['copy', 'csv', 'excel', 'pdf', 'print']
dom: 'Bfrtip',
buttons: [
{
text: 'Export to JSON',
action: function ( e, dt, node, config ) {
var data = dt.buttons.exportData();
$.fn.dataTable.fileSave(
new Blob( [ beautify(data , null, 2, 100) ] ),
'Families_'+ Date.now() +'.json'
);
}
}
,{
text: 'Export to CSV',
action: function ( e, dt, node, config ) {
var data = dt.buttons.exportData();
$.fn.dataTable.fileSave(
new Blob( [json2csv({ data: data.body, fields: null })]),
'Families_'+ Date.now() +'.csv'
);
}
}
]
then in both routes.js :
Router.route('/users', {
name: 'users',
action: function() {
var self = this;
$.getScript('https://cdn.datatables.net/buttons/1.2.4/js/dataTables.buttons.min.js', function(data, textStatus, jqxhr) {
if(jqxhr.status === 200) {
//self.render();
$.getScript('https://cdn.datatables.net/buttons/1.2.4/js/buttons.html5.min.js', function(data, textStatus, jqxhr) {
if(jqxhr.status === 200) {
self.render();
}
});
}
});
}
});

JQGrid data not being displayed

I have this code for my jqrid. But the data is not getting displayed in grid. The grids gets generated but no data is being shown in the grid. Also I have applied error control but that gives me no error. The code is as follows:
$(document).ready(function () {
'use strict';
var expHeadVal = "12345:Party;12346:Miscellaneous;12347:Conveyance;12348:Staff Welfare";
var webForm = document.forms[0];
var i = 0;
var mydata = "";
var jsonData = {
"records": "4",
"userData":{
},
"rows":[
{"id":"1", "sdate":"2013-03-22","expHead":"Party","expAmt":"1000","expReason":"Yes","expRemark":"FedEx"},
{"id":"2", "sdate":"2013-03-21","expHead":"Conveyance","expAmt":"200","expReason":"Yes","expRemark":"FedEx"},
{"id":"3", "sdate":"2013-03-20","expHead":"Conveyance","expAmt":"165","expReason":"Yes","expRemark":"FedEx"},
{"id":"4", "sdate":"2013-03-11","expHead":"Staff Welfare","expAmt":"1653","expReason":"Yes","expRemark":"FeEx"}
]
}
// alert (jsonData.rows[3].id);
var $grid = $("#View1"),
initDateWithButton = function (elem) {
if (/^\d+%$/.test(elem.style.width)) {
// remove % from the searching toolbar
elem.style.width = '';
}
// to be able to use 'showOn' option of datepicker in advance searching dialog
// or in the editing we have to use setTimeout
setTimeout(function () {
$(elem).datepicker({
dateFormat: 'dd-M-yy',
showOn: 'button',
changeYear: true,
changeMonth: true,
showWeek: true,
showButtonPanel: true,
onClose: function (dateText, inst) {
inst.input.focus();
}
});
$(elem).next('button.ui-datepicker-trigger').button({
text: false,
icons: {primary: 'ui-icon-calculator'}
}).find('span.ui-button-text').css('padding', '0.1em');
}, 100);
},
numberTemplate = {
formatter: 'number',
align: 'right',
sorttype: 'number',
editable: true,
searchoptions: { sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge', 'nu', 'nn', 'in', 'ni'] }},
dateTemplate = {
align: 'center',
sorttype: 'date',
editable: true,
formatter: 'date',
formatoptions: { newformat: 'd-M-Y' },
datefmt: 'd-M-Y',
editoptions: { dataInit: initDateWithButton, size: 11 },
searchoptions: {
sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'],
dataInit: initDateWithButton,
size: 11, // for the advanced searching dialog
attr: {size: 11} // for the searching toolbar
}
},
lastSel;
$grid.jqGrid({
datatype: "local",
data: jsonData,
jsonReader : {
// userdata: "userData",
root: "rows",
repeatitems: false,
// id: "1",
records: "records"
},
// data: jsonData,
colNames: ['Date','Expense Head','Amount', 'Reason','Remarks'],
colModel: [
// {name:'id', index:'id', width:15, editable:false, key: true, hidden: true},
{name:'sdate', index:'sdate', width:200, template: dateTemplate },
{name:'expHead', index:'expHead', width:150, editable:true, sorttype:'number',sortable:true, edittype:"select", editoptions:{value:expHeadVal}},
{name:'expAmt', index:'expAmt', width:100, editable:true, template: numberTemplate, summaryType:'sum' },
{name:'expReason', index:'expReason', width:200, editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"30"}},
{name:'expRemark', index:'expRemark', width:200,editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"30"}}],
loadtext: "Loading...",
sortname: ['Col0','Col1'],
pager: '#pView1',
caption: "Expense Table",
gridview: true,
rownumbers: true,
autoencode: true,
ignoreCase: true,
viewrecords: true,
sortorder: 'desc',
height: '100%',
editurl: 'clientArray',
beforeSelectRow: function (rowid) {
if (rowid !== lastSel) {
$(this).jqGrid('restoreRow', lastSel);
lastSel = rowid;
}
return true;
},
ondblClickRow: function (rowid, iRow, iCol, e) {
var p = this.p, $this = $(this);
// if the row are still non-selected
if ((p.multiselect && $.inArray(rowid, p.selarrrow) < 0) || rowid !== p.selrow)
{ $this.jqGrid("setSelection", rowid, true); }
$this.jqGrid('editRow', rowid, true, function () {
if (e.target.disabled)
{ e.target.disabled = false; }
$("input, select", e.target).focus();
});
return;
},
loadComplete: function () {
alert("OK");
},
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
}
});
$grid.jqGrid('gridResize', { minWidth: 450, minHeight: 150 });
$grid.jqGrid('navGrid', '#pView1', {refreshstate: 'current', edit: false, add: false, del: false});
$grid.jqGrid('inlineNav',"#pView1");
});
Can anybody tell me what is missing here?
Thanks for your help in advance.
Siddhartha
You should change data: jsonData to data: jsonData.rows because you use datatype: "local".
By the way jsonReader option will not used in case of datatype: "local". The format of data in jsonData.rows already corresponds default format of input data for datatype: "local". If you do will need to fill jqGrid having datatype: "local" with another format of data you should use localReader option instead of jsonReader (see the documentation).

URL field not working with flexigrid no response from URL

When I pass the URL I am getting a no response from the url otherwise if I specify the corresponding WCF service page which is included in my project it is working is it any cross domain issue what would be the possible issue
<form id="sform" runat="server">
<table id="flex2" style="display:none"></table>
<script type="text/javascript">
$(document).ready(function () {
var user_id = 1;
var data = { UserID: user_id };
$("#flex2").flexigrid({
useInlineEditor: true,
//singleSelect: true,
rowClick: function (row) {
//var r=this.DataSource.rows[row.rowIndex];
//var p=$(row).offset();
//alert(r[this.DataSource.key]+" "+r.Name+" offset:"+p.top+","+p.left);
//this.grid.inlineEditor.edit(row);
},
url: 'http://192.168.10.91:5001/Service.svc/GetStates',
method: 'POST',
dataType: 'json',
colModel: [
{ display: 'Hours', name: 'hours', width: 40, sortable: true, align: 'center' },
{ display: 'DOC', name: 'doc', width: 180, sortable: true, align: 'left' },
],
searchitems: [
{ display: 'Type', name: 'cmetype' }
],
onError: function (jqXHR, textStatus, errorThrown) {
alert("flexigrid failed " + errorThrown + jqXHR + textStatus);
},
sortname: "type",
sortorder: "asc",
usepager: true,
title: 'States',
useRp: true,
rp: 15,
showTableToggleBtn: true,
width: 800,
height: 200
});
});
//This function adds paramaters to the post of flexigrid. You can add a verification as well by return to false if you don't want flexigrid to submit
function addFormData() {
//passing a form object to serializeArray will get the valid data from all the objects, but, if the you pass a non-form object, you have to specify the input elements that the data will come from
var dt = $('#sform').serializeArray();
$("#flex2").flexOptions({ params: dt });
return true;
}
$('#sform').submit(function () {
$('#flex2').flexOptions({ newp: 1 }).flexReload();
return false;
});
</script>
</form>
Make sure that the svc service is accesibile and that it can accept post requests.
If all works well, check that the response is JSON and is valid.

Extjs MVC run function after store loads

I've got a grid getting data through a json store. I want to display the total number of rows in the grid. The problem is that the store.count() function is running before the store loads so it is returning 0. How can I get my count function to run only once the store has loaded? I'm working in MVC, here is my app.js which has my counting logic in it.
Thank you for any help
Ext.application({
name: 'AM',
appFolder: 'app',
controllers: [
'Users'
],
launch: function(){
Ext.state.Manager.setProvider(Ext.create('Ext.state.CookieProvider'));
Ext.create('Ext.container.Viewport', {
resizable: 'true',
forceFit: 'true',
layout: 'fit',
items:[{
xtype: 'userpanel',
}]
});
var port = Ext.ComponentQuery.query('viewport')[0],
panel = port.down('userpanel'),
grid = panel.down('userlist'),
label = panel.down('label');
var count = grid.store.getCount();
var labelText = "Number of people in list: " + count;
label.setText(labelText);
}
});
store code:
Ext.define('AM.store.Users', {
extend: 'Ext.data.Store',
model: 'AM.model.User',
autoLoad: true,
autoSync: true,
purgePageCount: 0,
proxy: {
type: 'rest',
url: 'json.php',
reader: {
type: 'json',
root: 'queue',
successProperty: 'success'
}
},
sortOnLoad: true,
//autoLoad: true,
sorters: [
{
property: 'PreReq',
direction: 'DESC'
},
{
property: 'Major1',
direction: 'ASC'
},
{
property: 'UnitsCompleted',
direction: 'DESC'
}
],
listeners:{
onload: function(){
var port = button.up('viewport'),
grid = port.down('userlist'),
panel = port.down('userpanel'),
label = panel.down('label'),
count = grid.store.getCount(),
labelText = "Number of people in list: " + count;
label.setText(labelText);
},
scope: this
}
});
grid code:
Ext.define('AM.view.user.List' , {
extend: 'Ext.grid.Panel',
alias: 'widget.userlist',
store: 'Users',
height: 'auto',
width: 'auto',
//resizable: 'true',
features:[{
ftype: 'grouping'
}],
autoFill: 'true',
layout: 'fit',
autoScroll: 'true',
initComponent: function() {
function renderTip(value, metaData, record, rowIdx, colIdx, store) {
metaData.tdAttr = 'data-qtip="' + value + '"';
return value;
};
var dateRender = Ext.util.Format.dateRenderer('m/d/Y');
this.columns=[
//code for all my columns
]
];
this.callParent(arguments);
}
});
Try putting a listener on the store then listen for the onload event get the count and update the field that way. Though there are many ways to do this that is just one.
But in the example above you never load the store you just create it, which is why you see zero.
figured it out, needed to add a listener for the "load" event, not "onLoad". Code below...
Ext.define('APP.store.Store', {
extend: 'Ext.data.Store',
model: 'APP.model.Model',
autoLoad: true,
autoSync: true,
purgePageCount: 0,
proxy: {
type: 'rest',
url: 'json.php',
reader: {
type: 'json',
root: 'users',
successProperty: 'success'
}
},
sortOnLoad:true,
sorters: [{
property: 'last',
direction: 'ASC'
}],
listeners: {
load:{
fn:function(){
var label = Ext.ComponentQuery.query('#countlabel')[0];
label.setText(this.count()+ ' Total Participants);
}
}
}
});