How do I return valid data from ajax call to DataTables child table? - datatables

I am returning data in json format from an ajax call to populate a child table that sits below the parent table. I get the following "DataTables warning: table id=child - Requested unknown parameter '1' for row 0, column 1. For more information about this error, please see http://datatables.net/tn/4". I have read the suggested information but unfortunately cannot relate it to my data. Any pointers in the right direction would be great please. The relevant code is:-
jQuery('#parent tbody').on( 'click', 'tr', function () {
var drno = (parentTable.row( this ).data()[4]);
jQuery.get("ajaxchild.php", {drno: drno}, function(data){
dataset = data;
//console.log(dataset) returns
/*
[["INV1","","2014-06-03","18.00","2.70"],["CRN6","","2014-10-20","6.00","0.90"],["REC4","","2014-06-20","13.80","0.00"],["REC5","","2014-10-24","5.00","0.00"],["P_C1","","2014-10-24","5.00","0.00"],["INV24","","2014-11-21","109.86","16.48"],["REC29","","2014-11-29","100.00","0.00"],["INV30","","2014-12-04","21.75","3.26"],["REC30","","2014-12-04","25.01","0.00"],["CRN23","","2014-12-04","21.75","3.26"],["REC34","","2014-12-20","1.16","0.17"],["REC40","","2015-01-30","200.00","0.00"],["REC44","","2017-02-15","5.00","0.00"],["REC45","","2017-02-15","10.00","0.00"]]
*/
var childTable = $('#child').DataTable( {
data: dataset,
columns: [
{ "title": "Reference" },
{ "title": "Our Ref." },
{ "title": "Date" },
{ "title": "Value" },
{ "title": "Tax" }
]
})
});
});
// Reload the child table when selecting parent row
// This will load the child table with the corresponding data
parentTable.on( 'select', function () {
childTable.ajax.reload();
} );
// Reload the child table when deselecting row
// The child script should return zero
// records to clear the table
parentTable.on( 'deselect', function () {
childTable.ajax.reload();
} );
Many thanks
Murray

Related

How to not trigger watch when data is modified on specific cases

I'm having a case where I do wish to trigger the watch event on a vue project I'm having, basically I pull all the data that I need then assign it to a variable called content
content: []
its a array that can have multiple records (each record indentifies a row in the db)
Example:
content: [
{ id: 0, name: "First", data: "{jsondata}" },
{ id: 1, name: "Second", data: "{jsondata}" },
{ id: 2, name: "Third", data: "{jsondata}" },
]
then I have a variable that I set to "select" any of these records:
selectedId
and I have a computed property that gives me the current object:
selectedItem: function () {
var component = this;
if(this.content != null && this.content.length > 0 && this.selectedId!= null){
let item = this.content.find(x => x.id === this.selectedPlotBoardId);
return item;
}
}
using this returned object I'm able to render what I want on the DOM depending on the id I select,then I watch this "content":
watch: {
content: {
handler(n, o) {
if(o.length != 0){
savetodbselectedobject();
}
},
deep: true
}
}
this work excellent when I modify the really deep JSON these records have individually, the problem I have is that I have a different upload methord to for example, update the name of any root record
Example: changing "First" to "1"
this sadly triggers a change on the watcher and I'm generating a extra request that isnt updating anything, is there a way to stop that?
This Page can help you.
you need to a method for disables the watchers within its callback.

How to update data after ajax reload using initComplete callback for DataTables when using ajax source data?

I’m using a select object to trigger an ajax reload for a DataTable.
I need to add individual column searching with select inputs for a given column (not for every column) but the select is filled with the previous ajax response.
How can I update the data that the initCompleteFunction callback uses to fill the select input in the individual column searching?
// this is the select that triggers the ajax.reload
$('#proveedor').on('change', function () {
$datatable
.DataTable()
.ajax
.reload(initCompleteFunction, false);
});
// this is my initCompleteFunction callback
function initCompleteFunction(settings, json){
var api = new $.fn.dataTable.Api( settings );
api.columns().every( function () {
var column = this;
if ($(column.header()).hasClass('select')) {
var select = $('<select><option value="">' + $(column.header()).html() + '</option></select>')
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
return false;
} );
//this is the part that keeps previous data insted of the new one from the ajax reload
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' );
} );
}
});
}
// and this is how I’m setting the DataTable
var $datatable = $('#table_materiales');
$datatable
.on('xhr.dt', function ( e, settings, json, xhr ) {
initCompleteFunction(settings, json);
})
.DataTable({
"ajax": {
"url": "http://my_endpoint",
"dataSrc": "",
"type": "POST",
"data": {
id_proveedor: function () {
return $('#proveedor').val(); // to get the value in the provider’s filter (select)
}
}
},
"columns": [
{
data: 'row_num'
},{
className: "select",
data: 'material'
},
// here goes the rest of the column definitions
],
"paging": false,
'columnDefs': [
{
'targets': 0,
'checkboxes': {
'selectRow': true
}
}
],
'select': {
'style': 'multi'
},
'order': [
[3, 'asc']
],
"createdRow": function (row, data, dataIndex) {
$(row).attr('data-id-material', data.id_material);
$(row).attr('data-pedido_sugerido', data.pedido_sugerido);
$(row).attr('id', 'id_' + data.row_num);
if(data['status_de_tiempo']=='FUERA'){
$(row).addClass('redClass');
}
},
});
During research I found that the xhr.dt event is triggered before the ajax.reload() is completed so the data keeps outdated when the select for the individual column search is populated. See this reference
User grozni posted this on April, 2019:
I have used console logs and was able to confirm that the event fires before the XHR event concludes, and does not pull the latest JSON. I used XHR tracking where I could to get around it but it's still really inconvenient and complicating matters alot. I need to be able to do certain things after the data is loaded and drawn. Perhaps it's worthy of a bug report
I found this post (See here) where user conangithub needed to
count DataTables item after I reload DataTable successfully
User lovecoding-git suggested this approach:
table= $('#example').DataTable();
$('#example').on('draw.dt', function() {
console.log(table.ajax.json().recordsTotal);
});
So, for my own issue, instead of
.on('xhr.dt', function ( e, settings, json, xhr ) {
initCompleteFunction(settings, json);
})
I wrote
.on('draw.dt', function ( e, settings, json, xhr ) {
initCompleteFunction(settings, json);
})
Et voilà.
I got the needed solution.

How to change the columns collection set of a kendo TreeList dynamically?

Try to change the columns list dynamically via a query ...
When I construct the TreeList, I call for columns :
$("#treelist").kendoTreeList({
columns: AnalyseCenterSKUService.getKPIColumnList($scope)
If I return a simple array with the fields, it's working ..
If I call a $http.get (inside my getKPIColumnList(..) function) which add some columns to the existing array of columns, the TreeList is not constructed correctly.
Any suggestion will be really appreciated ! :)
EDIT 22-10-2019 09:00
Treelist init
$("#treelist").kendoTreeList({
columns: AnalyseCenterSKUService.getKPIColumnList($scope),
scrollable: true,
columnMenu : {
columns : true
},
height: "100%",
dataBound: function (e) {
ExpandAll();
},
dataSource: {
schema: {
model: {
id: "id",
parentId: "parentId",
fields: {
id: { type: "number" },
parentId: { type: "number", nullable: true },
fields: {
id: { type: "number" },
parentId: { type: "number", nullable: false }
}
}
}
},
transport: {
read: {
url: "/api/AnalyseCenter/GetWorkOrderTree/0",
dataType: "json"
}
}
}
The getKPIColumnList return an static array + some push with dynamic columns (from DB)
angular.module('AnalyseCenterDirectives')
.service ('AnalyseCenterSKUService', function ($http) {
var toReturn = [ {field: "Name", title: "Hiérachie SKU", width: "30%" }, ..., ..., .... ];
I try in this function to push DB result
return $http.get("/api/AnalyseCenter/GetWorkOrderHistorianAdditonalColumns?equipmentName=" + equipmentName)
.then(function (result) {
var data = result.data;
if (data && data !== 'undefined') {
var fromDB = data;
angular.forEach(fromDB, function (tag) {
var tagName = tag.replace(".","_");
toReturn.push({
field: tagName, title: tag, width: '10%',
attributes: { style: "text-align:right;"} })
})
The stored procedure GetWorkOrderHistorianAdditonalColumns returns a list of string (future column)
That is because ajax is async, that means your tree list is being initialized before the request finishes. A classic question for JavaScript newcomers. I suggest you take a while to read about ajax, like How does AJAX works for instance.
Back to your problem. You need to create your tree list inside the success callback(I can't give you a more complete solution since I don't know what you're doing inside your function or which framework you're using to open that ajax request) with the result data, which is probably your columns. Then it would work as if you're initializing it with arrays.

Jquery Datatables expand row and get detail via Ajax

Is it possible to get the detail for each row through Ajax?
I found a starting point here:
http://datatables.net/release-datatables/examples/api/row_details.html
but it doesn't use ajax.
I'm thinking about modifying fnFormatDetails() function and place the ajax call there.
But i'm looking for another better answer.
Thanks.
It's very simple. All you have to do is put your details in a separate field within the "data" array:
E.g. your JSON might look like as follows:
{
"draw": "${drawId}",
"recordsTotal": "${totalRecords}",
"recordsFiltered": "${filteredRecords}",
"data": [
{
"empName": "${employee.name}",
"empNumber": "${employee.number}",
"empEmail": "${employee.email}",
"extraDetails" : [
["${employee.salary}", "${employee.title}"]
]
}
]
}
Then in your javascript, you can simply access this extra details by using JavaScript arrays. E.g.
var row = employeeTable.row( tr );
var rowData = row.data();
alert(rowData.extraDetails[0][0]);
alert(rowData.extraDetails[0][1]);
You need not to go for ajax if you have the data in your row.
Try oTable.fnGetData(rowIndexor|trNode)
you can try this and it will work.
First: create your datatable.
var table = $('#myTable').DataTable( {
ajax: '/api/staff',
columns: [
{
className: 'details-control',
orderable: false,
data: null,
defaultContent: ''
},
{ data: "name" },
{ data: "position" },
{ data: "office" },
{ data: "salary" }
],
order: [[1, 'asc']] } );
Second: Event handlers
$('#myTable tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
row.child.hide();
tr.removeClass('shown');
}
else {
row.child( format(row.data()) ).show();
tr.addClass('shown');
} } );
Third: Ajax request and formatting the response
function format ( rowData ) {
var div = $('<div/>')
.addClass( 'loading' )
.text( 'Loading...' );
$.ajax( {
url: '/api/staff/details',
data: {
name: rowData.name
},
dataType: 'json',
success: function ( json ) {
div
.html( json.html )
.removeClass( 'loading' );
}
} );
return div; }
you can pass any row argument to format method.
Check This For More Details

Store filter in sencha touch

I have store having structure :
Ext.create('Ext.data.Store', {
fields: [
'title'
],
data: [{
title: 'ABC'
}, {
title: 'ABC2'
}, {
title: 'ABC3'
}, {
title: 'ABC4'
}, {
title: 'ABC5'
}, {
title: 'ABC6'
}]
});
So when I load this store List get populated with all 6 records.
I just wanted to Filter this store on button click I just wanted to get some selected record out of this 6 record Can It be possible.
Provide me Some Idea or Working code.
To filter the store based on title
Ext.getStore('storeId').filter("title", "ABC3");
To clear filter
Ext.getStore('storeId').clearFilter();
See store filter doc
Update
Ext.getStore('storeId').filterBy(function(record){
var title = record.get('title');
if(title == "ABC" || title == "ABC1" || title == "ABC2")
return record;
});
My approach is to set a filter on the store when I tap on the button. In my case it was a selectfield and on the change event I filter compared to the current value in the selectfield
onChangeStatusSelectfield: function (newValue, oldValue) {
var store = Ext.getStore('CustomVacationRequest');
console.log('Accepted Filter');
newValue = this.getStatusSelectfield().getValue();
console.log(store, newValue);
store.clearFilter();
if (store != null);
store.filter(function (record) {
if (newValue == record.data.status) { //your data from the store compared to
//the value from the selectfield
return true;
}
Ext.getCmp("VacationRequestsManagerList").refresh() //refresh your list
});
},
This is just my part of the controller. Handle events and buttons and stores at your own choice&need. Good luck!