Server side pagination in KTDatatable (Metronic) - javascript

I am new to KTDatatable in Metronic.
I am trying to use server side pagination in Metronic dashboard, and I am parsing the data in a KTDatatable, but I can't find a way to parse the returned data from the API and to view number of pages and each page URL.
The code that I was able to write so far is:
data: {
type: 'remote',
source: {
read: {
url: dataURL,
method: 'GET',
contentType: 'application/json',
map: function(data) {
var cards = data.cards.data;
var currentPage = data.cards.current_page;
var lastPage = data.cards.last_page;
return cards;
}
},
},
pageSize: 10,
serverPaging: true,
},
In this code I was able to get the first ten records but:
1- I wasn't able to parse them the way I want in the table.
2- I wasn't able to show the pages number nor calling the API for the second page or the (x) page I want.
These are the things I want to do.
Thanks in advance.

You can go back to the end of the KT-Datatable documentation to find most of answers you want KT-Datable documentation, but I am gonna explain more hoping it will be more clear.
So the returned value from the API (Json) should look have two main objects meta and data, and it looks something like this:
{
"meta": {
"sort": "desc",
"field": "IssueName",
"page": 1,
"pages": 2,
"perpage": "10",
"total": 11
},
"data": [
{
"IssueName": "******",
"CardNumber": "******"
},
{
"IssueName": "******",
"CardNumber": "******"
}
]
}
And after getting the values of the response from the API you should only return the data object to be parsed by the datatable so the map function should look something like this:
map: function(data) {
return data.data;
}
and it will process the meta data itself.
To parse the data into the columns you should use the same key name of the data in column definition array, so in my example I used it like this:
columns: [
{
field: 'IssueName',
title: columnsTitles.issue,
type: 'string',
},
{
field: 'CardNumber',
title: columnsTitles.card_number,
type: 'string',
},
]
And every time the datatable calls the API it will send more data that will help you give the right response, the data will be on a shape of an array (The field name should be the same as the key):
[
"pagination" => array:4 [
"page" => "1"
"pages" => "2"
"perpage" => "10"
"total" => "11"
],
"sort" => array:2 [
"field" => "IssueName"
"sort" => "desc"
],
]
The sent data is related with the pagination and sorting type you have to get from the API, and you can also add filters and they will be stored in the array in the "query" field, and you can handle them in the backend.

Related

ext 7 chart proxy data format

I try to load json data with direct proxy on a cartesian chart in ext 7 like this:
https://fiddle.sencha.com/#view/editor&fiddle/3bae
In this example I load data from ajax but the return data is the same. (its actually copy pasted from my direct api). I have the same result on my testsystem: I can load hardcoded data but not from proxy.
How do I have to format the data so it populates my chart?
the root property of your JSON must be 'result.data'
the data are object, NOT an Array
For yor custom JSON you can write reader transformer, something like this:
...
...
proxy: {
type: 'ajax',
url: 'test.json',
reader: {
type: 'json',
rootProperty: 'data',
fields: ['month', 'value'], // What is it?
transform: {
fn: function (data) {
return Object.values(data.result.data);
},
scope: this
}
}
},
autoLoad: true
});
Or you can change the backend to generate standard extjs json, sample:
{
"users": [
{
"id": 1,
"name": "Ed Spencer",
"email": "ed#sencha.com"
},
{
"id": 2,
"name": "Abe Elias",
"email": "abe#sencha.com"
}
]
}

JS datatabe with Array edit

I has create HTML page, with user entry data in page then upload to SQL server.
I has study DataTable to load array to table, try edit still not , has any one can help?
var array = ['54 GR', '89 GR', 'Internal Transfer', 'Putaway']
$('#example').DataTable({
data: array,
"searching": false,
columns: [{
"data": 0,
"title": "Date"
}, {
"data": 1,
"title": "Account"
}, {
"data": 2,
"title": "Type"
}, {
"data": 3,
"title": "OPDeployed",
"render": function(data, type, row, meta) {
return "<input type='text' value=''/>";
}
}]
});
Its really difficult to say without being able to see the page or even the code. All I can really say is that the load order should be:
jQuery
jQuery UI
DataTables
2 and 3 can be swapped and you shouldn't load more than one of each.

Add fields in DevExpress Pivot using AngularJS

I'm looking at this template to build a web application: https://js.devexpress.com/Demos/WidgetsGallery/Demo/PivotGrid/FieldChooser/AngularJS/Light/
In the example there are static data. I have to retrieve them from the server. So, I wrote this:
$scope.testData = [];
$scope.pivotGridDataSource = new DevExpress.data.PivotGridDataSource({
fields: [{
caption: "Nome",
dataField: "fullName",
area: "row"
}, {
caption: "Country",
dataField: "country",
area: "column"
}, {
caption: "Count",
dataField: "countOne",
dataType: "number",
summaryType: "sum",
area: "data"
}],
store: $scope.testData
});
$scope.pivotGridOptions = {
allowSortingBySummary: true,
allowSorting: true,
allowFiltering: true,
showBorders: true,
dataSource: $scope.pivotGridDataSource,
fieldChooser: {
enabled: false
}
},
$scope.fieldChooserOptions = {
dataSource: $scope.pivotGridDataSource,
texts: {
allFields: "All",
columnFields: "Columns",
dataFields: "Data",
rowFields: "Rows",
filterFields: "Filter"
},
width: 400,
height: 400,
bindingOptions: {
layout: "layout"
}
};
// Now I call the server to retrieve data
$scope.getTestData = () => {
$scope.testData.length = 0;
result.forEach(e => {
$scope.testData.push(e);
);
$scope.pivotGridDataSource.reload();
}
$scope.getTestData();
The problem is that when the data are loaded, in the Fields below it shows just the fields written at the beginning (so the name, the count and the country). But I saw in the demo that it should be display ALL parameters of the object.
For example, if the object is so structured:
{ "name": "Test1", "country": "Germany", "creationDate": "xxx", "surname": "yyy" }
So, I expect that in the fields there should be ALL parameters, so name, country, creationDate, surname. So, I did this at the beginning:
I changed $scope.testData = [] into:
$scope.testData = [{ "name": "", "country": "", "creationDate": "", "surname": "" }]
so the component will preparare all fields. And this works. But what if the server gives me back an Object that has another parameters? How can I display them?
I tried so after the calling and before the reload():
let fields = $scope.pivotGridDataSource.fields();
let newField = {
llowExpandAll: false,
allowFiltering: true,
allowSorting: true,
allowSortingBySummary: true,
caption: "This is a new field",
dataField: "newField",
dataType: "string",
displayFolder: "",
index: fields.length
}
$scope.pivotGridDataSource.fields().push(newField);
$scope.pivotGridDataSource.reload();
But it doesn't work yet. Worse, it does not even initialize the Pivot.
The fieldChooser uses the store fields, in this case $scope.testData fields, in your code I see your store is first declared (as null or with some format as you described) and then you have a function to fill it.
I don't know how your code looks and why you create your store that way, but that is basically your problem (the flow).
In the sample code the flow is:
Store with data (static in this case)
PivotGridDataSource
FieldChooser
In your code the flow is:
Store (empty)
PivotGridDataSource
FieldChooser
Store (fill) --> at this point your FieldChooser has been initialized with the fields of the empty version of your store so not much to do (in Jquery you could re-create your object, you dan do it using Jquery within AngularJs see a simple code sample here and below)
$('#chartContainer').dxChart('instance').dispose();
$('#chartContainer').dxPieChart({
...
});
To avoid all of this you can just use the DevExpress.data.CustomStore and your flow will be basically identical to the demo.

DataTables - Format returning ajax data

I am working on this example from DataTables.net but I have made modification so that it works with my ajax call to my API.
My problem is that my API returns the DateTime values like this...
Created=2015-02-13T00:00:00
I need to be able to convert that to just be just the date without the time for my table (hopefully without changing the API). I have tried everything that I know to try. I am still sort of a beginner at this advanced javascript stuff. I was trying to do just a simple substring but I dont think that is working. Well at least how I was trying anyways.
Thanks for anything help!
DataTables v1.10.5
Jquery v1.11.2 (due to need to support IE8)
Original Problem Code:
$(document).ready(function () {
var table = $('#AllHuddleRecords').DataTable({
"ajax": "../api/huddle/posts",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data" : "EmpName" },
{ "data": "Created" },
{ "data" : "PriorityName" },
{ "data" : "TopicName" }
]
});
Thanks to the guidance of cmxl...here is the working code...
var table = $('#AllHuddleRecords').DataTable({
"ajax": "../api/huddle/posts",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data" : "EmpName" },
{ "data": "Created" },
{ "data" : "PriorityName" },
{ "data" : "TopicName" }
],
"columnDefs": [
{
"render" : function (data, type, row) {
return new Date(data).toLocaleString();
},
"targets": 2
}
]
});
You can hook in to the column rendering event. See the documentation here:
https://datatables.net/examples/advanced_init/column_render.html
$(document).ready(function() {
$('#example').dataTable( {
"columnDefs": [
{
// The `data` parameter refers to the data for the cell (defined by the
// `data` option, which defaults to the column being worked with, in
// this case `data: 0`.
"render": function ( data, type, row ) {
return data.slice(0, data.indexOf('T'));
},
"targets": 0
},
{ "visible": false, "targets": [ 3 ] }
]
} );
} );
Or if you want to parse the string as a date you can refer to this answer here:
Converting string to date in js
//...
"render": function ( data, type, row ) {
return new Date(data).toString();
}
//...
Here you can look even deeper into the Date object in Javascript:
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date
Is it possible to do some pre-processing on your data before you send it to data tables, for example if you are inserting the following data into your data table, use Date.parse() on each element of your data to convert to the desired format?
var ajaxData = {
"data": [{
"EmpName": "Bob",
"Created": "2015-02-13T00:00:00",
"PriorityName": "Priority1",
"TopicName": "Topic1"
}]
};
$(ajaxData.data).each(function() {
var dateMillis = new Date(this.Created);
this.Created = dateMillis.getMonth() + "/" + dateMillis.getDay() + "/" + dateMillis.getFullYear();
});
Note that if you want to sort on your date column, then the solution may well be to pre-process data and convert dates to milliseconds using Date.parse() and then use render to convert the date to readable format as cmxl suggested. Good luck!

Howto convert JSON to Array

This is my first question to StackOverflow. I think answer is not so complicate, but I am very new to Javascript.
I have a JQuery AJAX function that parses this JSON object:
{
"Users":[
{
"key":"1",
"label":"Tom Clancy"
},
{
"key":"12",
"label":"Steve Martin"
}
]
}
and should obtain the same result as:
var sections = [{
key: 1,
label: "Tom Clancy"
}, {
key: 12,
label: "Steve Martin"
}
];
I'm able to iterate through JSON element, but i don't know how to go on.
Can you provide suggestions?
EDIT: i can't still get it work...this is my code:
var sections=[
{key:1, label:"Section A"},
{key:2, label:"Section B"},
{key:3, label:"Section C"},
{key:4, label:"Section D"}
];
$.ajax({
url: '/WebOffice/ListaUtenti',
type: "POST",
dataType: 'json',
success: function (data)
{
console.log( "success" );
sections = data.Users;
}});
scheduler.createTimelineView({
name: "matrix",
x_unit: "day",
x_date: "%d %M",
x_step: 1,
x_size: 15,
y_unit: sections,
y_property: "section_id"
});
The jquery ajax call doesn't assign the new value to sections (the call state is success, verified) and so scheduler still shows the original sections. Where i'm wrong?
thanks
I will explain you the process. Go to any online JSON formatter, may be this one and pretty print your JSON. It will appear as.
{
"Users":[
{
"key":"1",
"label":"Tom Clancy"
},
{
"key":"12",
"label":"Steve Martin"
}
]
}
So Users is an array of objects. Users[0] is first object and Users[1] is second object.
So you can iterate the JSON easily and obtain the result you want.
Live demo : http://jsfiddle.net/sbymr/
See the console for the output.

Categories

Resources