I am using jquery datatable in my application, plugin link https://datatables.net/
I want to populate my datatable with JSON, but I am failed.here is my code.
HTML:
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Code</th>
<th>Description</th>
<th>isActive</th>
</tr>
</thead>
<tfoot>
<tr>
<th>id</th>
<th>Name</th>
<th>Code</th>
<th>Description</th>
<th>isActive</th>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
JS:
$(document).ready(function() {
console.log("hi ready");
$('#example').DataTable({
retrieve: true,
ajax: {
url: '/ProductLicensingApplication/feature/list',
dataSrc: ''
},
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "code" },
{ "data": "description" },
{ "data": "isActive" }
]
});
} );
my json
but I am not able to populate data into the table as the table shows no data available in the table..you can see in the image
please tell me what is the problem in my code...
As written in documentation. The ajax.dataSrc option is used to tell DataTables where the data array is in the JSON structure. An empty string is a special case which tells DataTables to expect an array.
In your case JSON is an object and you should set dataSrc : 'features'
Ahmad,
Either set dataSrc : 'features' or if possible rename the attribute name 'features' to 'data' in the response data.
Related
I tried using datatables for live data but my problem is, every time my data updates, I can't use searching and every time I use pagination, it goes back to first page. Can somebody knows what datatable plugin is compatible with angular?
Here is my code for realtime update of data:
angular.module('selectExample', [])
.controller('ExampleController', ['$scope','$interval', function($scope,$interval) {
$interval(function () {
$scope.register = {
regData: {
branch: {},
},
names: [
{name:"narquois"},{name:"vorpal"},{name:"keen"},
{name:"argol"},{name:"long"},{name:"propolis"},
{name:"bees"},{name:"film"},{name:"dipsetic"},
{name:"thirsty"},{name:"opacity"},{name:"simplex"},
{name:"jurel"},{name:"coastal "},{name:"fish"},
{name:"kraken"},{name:"woman"},{name:"limp"},
],
};
}, 1000);
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="selectExample" ng-controller="ExampleController">
<table id="example" width="100%">
<thead>
<tr align="center">
<th>Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in register.names">
<td align="center">{{ person.name }}</td>
</tr>
</tbody>
</table>
</div>
Enable state saving and override state save/load handlers to use only the table's DOM id:
$('#example').dataTable( {
stateSave: true,
stateSaveCallback: function(settings,data) {
localStorage.setItem( 'DataTables_' + settings.sInstance, JSON.stringify(data) )
},
stateLoadCallback: function(settings) {
return JSON.parse( localStorage.getItem( 'DataTables_' + settings.sInstance ) )
}
} );
You have to initialize your DataTable with the option stateSave. It enables you to keep the pagination, filter values, and sorting of your table on page refresh. It uses HTML5's APIs localStorage and sessionStorage.
$('#example').dataTable( {
stateSave: true
});
Trying to get my ajax to load into data tables. I want to load 2 tables from the same ajax call but I can't even get 1 to load first. Let's get some snippet action going...
$(function() {
$("#tablepress-1").DataTable({
ajax: {
url: '/api/?action=getStats',
dataSrc: 'data',
"deferRender": true
},
"columns": [{
"instances": "Strategy"
},
{
"instances": "Exchange"
},
{
"instances": "Trades"
},
{
"instances": "PL"
},
{
"instances": "Uptime"
}
]
})
})
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="tablepress-1" class="tablepress tablepress-id-1">
<caption style="caption-side:bottom;text-align:left;border:none;background:none;margin:0;padding:0;">Edit</caption>
<tbody>
<tr class="row-1">
<td class="column-1">Strategy</td>
<td class="column-2">Exchange</td>
<td class="column-3">Trades</td>
<td class="column-4">PL</td>
<td class="column-5">Uptime</td>
</tr>
</tbody>
</table>
Since stack snippets don't support ajax data, I'll paste it here:
{"success":true,"data":{"instances":[{"Strategy":"...","Exchange":"...","Trades":"...","PL":"...","Uptime":"..."}],"trades":[{"Open":"...","Strategy":"...","Exchange":"...","Direction":"...","Size":"...","PL":"...","Close":"...","ID":"..."}]},"meta":{"botOnline":true,"threadCount":0,"balance":0.0028}}
Right now I just have my script outputting ... for each field. What happens is that the table headings disappear and no data ever gets loaded into the table.
I tried setting up a fiddle with the data source but it's my first time trying to use the echo feature. Maybe someone else knows how to do that: https://jsfiddle.net/Trioxin/kjhtn7wm/6/
I can't imagine what's wrong here. I thought I specified the json format properly but it appears not.
Regarding cross domain AJAX sources in jsfiddles you can use http://myjson.com
Your "table headings" disappear because they are not table headings. They are just a <tbody> row that will be removed as soon DataTables get some data. Do this instead:
<thead>
<tr class="row-1">
<th class="column-1">Strategy</th>
<th class="column-2">Exchange</th>
<th class="column-3">Trades</th>
<th class="column-4">PL</th>
<th class="column-5">Uptime</th>
</tr>
</thead>
You must either pass an array of objects or point to the path of that array, like dataSrc: data.instances. You could also have dataSrc: function(data) { return data.data.instances }
You define which object property that should be mapped into which column through the data option like { data: "Strategy" }:
columns: [
{ data: "Strategy" },
{ data: "Exchange" },
{ data: "Trades" },
{ data: "PL" },
{ data: "Uptime" }
]
forked fiddle -> https://jsfiddle.net/hfc10sxt/
I have a json array coming from a url:
http://blahblahblah.com/company/all, like this:
in angularjs controller, i have something like this:
$('#example-1').DataTable({
"ajax" : 'http://blahblahblah.com/company/all',
"columns": [
{"data": "companyId"},
{.....}, // I can't assign "data" name to array because it is already unnamed.
]
});
Traversing in html table_id example-1
<table id="example-1" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Company</th>
<th>Legal Name</th>
<th>DBA Name</th>
<th>Formation</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Company</th>
<th>Legal Name</th>
<th>DBA Name</th>
<th>Formation</th>
</tr>
</tfoot>
Output:
So, my question is how do I identify the column names from above UNNAMED JSON ARRAY mentioned on top of the question, and display it in html table. Waiting for your kind response.
I am thinking to do something like this
$(document).ready(function() {
$('#example').DataTable( {
"ajax": "http://blahblahblah.com/company/all",
"columns": [
{ "data": "companyId" },
{ "data": "legalName" },
{ "data": "dbaName" },
{ "data": "formation"}
]
} );
} );
you need to add more information to the datatable while intializing what are the keys to be shown. form more details check datatable objects
I was unable to identify the correct syntax of identifying and using the column names in my JSON array, which I did like this, and solved my problem. So now the data is displayed fine in my table, this way:
$.getJSON('http://blahblahblah/company/all', function(data) {
$('#companies').DataTable({
"aaData": data,
"aoColumns": [
{"mDataProp":"companyId"},
{"mDataProp":"legalName"},
{"mDataProp":"dbaName"},
{"mDataProp":"formation"}
]
});
});
I also added hyperlink to companyId like this:
$.getJSON('http://blahblahblah/company/all', function(data) {
var companyId = null;
$('#companies').DataTable({
"aaData": data,
"aoColumns": [
{"mDataProp":"companyId", "render": function(data, type, row, meta) {
if( type==='display' ) {
companyId = data;
data = '' + data + '';
}
return data;
}},
{"mDataProp":"legalName"},
{"mDataProp":"dbaName"},
{"mDataProp":"formation"}
]
});
});
I am thankful to all of you for helping me grab the track.
Thanks.
Actual way to do this is to use ng-repeat in the data array. And for the data fetch, use an angular service with a promise.
In the Controller
var self = this;// this is the controller which is aliased as ctrl at routing
var theData = yourService.FetchData(params).then(function(data){
self.tableData = data; // not going for the exact implementation.
},function(err){
manageError(err);// manage your errors here.
}));
In the HTML
<table id="example-1" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Company</th>
<th>Legal Name</th>
<th>DBA Name</th>
<th>Formation</th>
</tr>
</thead>
<tr ng-repeat="var item in ctrl.tableData ">
<td>{{item.companyId}}</td>
<td>{{item.legalName}}</td>
<td>{{item.dbaName}}</td>
<td>{{item.formation}}</td>
</tr>
</table>
I have my html code like this defining a footable
<table class="table toggle-circle" id="exampleRowToggler">
<thead>
<tr>
<th data-field="marca">Marca</th>
<th data-field="modelo">Modelo</th>
<th data-field="placa">Placa</th>
<th data-field="chasis">Chasis</th>
<th data-field="vigencia_desde">Vigencia Desde</th>
<th data-field="vigencia_hasta">Vigendia Hasta</th>
<th data-hide="all">Clausulas</th>
<th data-hide="all">Exclusiones</th>
<th data-hide="all">Beneficios</th>
<th data-hide="all">Deducibles</th>
<th data-hide="all">Coberturas</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
and I want to fill it from a .js file that contains a function with the data in json like this. I've tried some options but still can't get it and the last thing I've tried was this.
loadTable: function () {
var bt_data = [{
"marca": "HYUNDAI",
"modelo": "IONIQ",
"placa": "T02096577",
"chasis":"KMHC851CGHU029520",
"vigencia_desde":"22/05/2017",
"vigencia_hasta":"22/05/2018",
"clausulas": "clauuuuuusulaaas",
"exclusiones": "eeexclusioooonesss",
"beneficios": "beeeeneeefiiiciiiooosss",
"deducibles":"deeeeduuuuciiiibleeeessss",
"coberturas":"cooooobeeeertuuuuraaaasssss"
}];
$('#exampleRowToggler').footable({
"useParentWidth": true,
"columns": $.get('columns.bt_data'),
"rows": $.get('rows.bt_data')
});
}
help me please.
The columns and rows values that you are passing in to footable will be producing nothing at all unless you have a server side page listening for the "columns.bt_data" and "rows.bt_data" URLs and returning relevant JSON/array responses.
Here's what I think you wanted to do:
loadTable: function () {
var bt_data = [{
"marca": "HYUNDAI",
"modelo": "IONIQ",
"placa": "T02096577",
"chasis":"KMHC851CGHU029520",
"vigencia_desde":"22/05/2017",
"vigencia_hasta":"22/05/2018",
"clausulas": "clauuuuuusulaaas",
"exclusiones": "eeexclusioooonesss",
"beneficios": "beeeeneeefiiiciiiooosss",
"deducibles":"deeeeduuuuciiiibleeeessss",
"coberturas":"cooooobeeeertuuuuraaaasssss"
}];
//get Column JSON from first item in Rows array
var columnJSON = $.map(Object.getOwnPropertyNames(bt_data[0]), function (column) {
return {"name": column,"title": column}
});
$('#exampleRowToggler').footable({
"useParentWidth": true,
"columns": columnJSON, //Pass columns object through to footable
"rows": bt_data //Pass your existing rows array through to footable
});
}
I tried for a while to "integrate" datatables.net (https://datatables.net/) with a Vue app.
Eventually I stumbled on comments that essentially suggest not so much to try integration, but rather, leverage jquery modules as-in and "hook" them in via a mounted/created event.
So, in that vein, I have the following code nearly working
<template>
<table aria-describedby="feedback-history_info" role="grid" id="feedback-history" class="table table-bordered table-striped dataTable">
<thead>
<tr role="row">
<th>ID</th>
<th>Created Date</th>
<th>Project</th>
<th>Reviewer</th>
<th>Status</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th colspan="1" rowspan="1">Created Date</th>
<th colspan="1" rowspan="1">Project</th>
<th colspan="1" rowspan="1">Reviewer</th>
<th colspan="1" rowspan="1">Status</th>
</tr>
</tfoot>
</table>
</template>
<script>
import $ from 'jquery'
// Require needed datatables modules
require('datatables.net')
require('datatables.net-bs')
import moment from 'moment'
export default {
name: 'Feedback',
data() {
return {}
},
mounted() {
$('#feedback-history').DataTable({
"ajax": "/index.sjs?list",
"processing": false,
"serverSide": true,
"columns": [
{
"data": "id"
},
{
"data": "created"
},
{
"data": "projectName"
},
{
"data": "reviewer"
},
{
"data": "status"
}
],
"columnDefs": [{
"render": function(data, type, row) {
return moment(parseInt(data)).format('MMMM Do YYYY');
},
"targets": 1
},
{
"render": function(data, type, row) {
// I want to use router-link similar to following
return `<router-link :to="{ name: 'FeedbackEdit', params: { feedbackId: ${ row.id } }}">${ row.projectName }</router-link>`
// To render as ...
// ${data}
},
"targets": 2
},
{
"visible": false,
"targets": [0]
}
]
})
}
}
</script>
<style>
</style>
Only issue is in the rendering of links in my datatable cells. As I'm using vue-router, I need to vue-router via router-link to "handle links". (See comments in code).
Any help is appreciated.
In the end, I did not use router-link.
Rather I used vuex and saved enough session information to the vuex store such that on page refresh I could re-render the view appropriately.
While technically this is a page refresh or "page flip" and not the reactive SPA-way of using the DOM (or shadow-DOM) to manipulate the view, it does give a near-enough experience in the absence of a better approach.