Datatables Not Loading Nested Objects Ajax - javascript

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/

Related

Datatable for pagination and searching for live data?

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
});

How to display json array coming from url through ajax in angularjs

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>

Render complicated Array into Datatables

I Have a really complicated Array that I want to display in DataTables in order to do some research and csv export.
An extract here of one page : https://api.myjson.com/bins/w8pzl
This is the structure :
[
[
{
title : "title",
stacks: {
stackname : "stackname",
stackValue : [
"value1","value2","value3"
]
},
..... multiple article
],
.....multiple pages
]
I don't know neither how to structure the table nor how to populate it.
My first try so far :
<div id="page-content-wrapper">
<div class="container">
<div class="row">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Stackname</th>
<th>stackvalue</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('#example').DataTable({
"processing" : true,
"ajax" : {
"url" : "/",
dataSrc : ''
},
"columns" : [ {
"data" : "stackName"
}, {
"data" : "stackValue[,]"
}]
});
});
</script>
But it looks like I have to go through the all document to get my information..
If it's just not possible... I've done an easier version of my structure :
[
[
{
title : "title",
stacks: [
"value1","value2","value3"
]
},
..... multiple article
],
.....multiple pages
]
But still impossible to parse it.. i'm struggling with the two first array..
Edit with answer
Thanks to the help of the selected answer post I managed to get this code working :
$('#example').DataTable( {
"processing" : true,
"ajax": {
"url": "/",
"dataSrc" : function ( json ) {
return json.reduce(function(a, b) {
return a.concat(b)
}).map(function(value) {
return value.stacks
})
.reduce(function(a, b) {
return a.concat(b)
})
}
}
,... other configuration
You can use the ajax.dataSrc option as a function to manipulate the data returned from the server.
ajax.dataSrc
function ajax.dataSrc( data )
As a function dataSrc provides the ability to manipulate the data returned from the server from one form into another. For example, if your data is split over multiple arrays you might combine it into a single array to return for processing and display by DataTables. ...
Here is an example.
$('#example').DataTable( {
"ajax": {
"url": "https://api.myjson.com/bins/w8pzl",
"dataSrc" : function ( json ) {
return json[0].map(function(value) {
return value.stacks
})
.reduce(function(a, b) {
return a.concat(b)
})
}
},
"columns": [
{ "data": "stackName" },
{ "data": "stackValue[, ]" }
]
});
<link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Stackname</th>
<th>stackvalue</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Stackname</th>
<th>stackvalue</th>
</tr>
</tfoot>
</table>

how to populate jquery datatables with json?

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.

How to use vue-router and router-link to handle links dynamically created in jquery modules such a datatables?

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.

Categories

Resources