Datatable does not works with Firebase - javascript

I am trying to display data in data in Datatable and allow the user to download in desired format. But it does not seem to work my data neither gets displayed nor gets downloaded. This is the code am using at the moment.
document.addEventListener("DOMContentLoaded", function(event) {
var dTable=$('#ex-table').DataTable({
"bDestroy": true,
dom: 'lfrtipB',
buttons: [
{
extend: 'copyHtml5',
title: 'Records'
},
{
extend: 'csvHtml5',
title: 'Records'
},
{
extend: 'excelHtml5',
title: 'Records'
},
{
extend: 'pdfHtml5',
title: 'Records'
},
'print'
],
lengthMenu: [[5, 20, 50, -1], [5, 20, 50, "All"]]
});
});
var databaseRef = firebase.database().ref("users/");
var table = $('#ex-table').DataTable();
databaseRef.on("child_added", function(data) {
var storageObj = data.val();
var dataSet = [storageObj.Department, storageObj.EmpId, storageObj.Name, storageObj.Position];
table.rows.add([dataSet]).draw();
});
Here is the codepen https://codepen.io/jagrutitiwari/pen/WYBWVy for the code I am trying. Where am I going wrong?
Update:
Screenshot of my users node:
Update2
Security rules:
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
Update 3
If I add dataSrc to Datatable it works but I cannot see the exports buttons in Datatable now.
document.addEventListener("DOMContentLoaded", function(event) {
var dTable=$('#ex-table').DataTable({
"bDestroy": true,
dom: 'lfrtipB',
data: dataSrc,
buttons: [
{
extend: 'copyHtml5',
title: 'Records'
},
{
extend: 'csvHtml5',
title: 'Records'
},
{
extend: 'excelHtml5',
title: 'Records'
},
{
extend: 'pdfHtml5',
title: 'Records'
},
'print'
],
lengthMenu: [[5, 20, 50, -1], [5, 20, 50, "All"]]
});
});

With your security rules, your users need to be authenticated in order to read (and write to) the database.
With the code you show in your question (an excerpt of your entire HTML page, I guess), it seems that you don't ask the users to authenticate, therefore you don't get any record when you query the database.
You should either integrate an authentication mechanism, for example using FirebaseUI Auth (see https://github.com/firebase/firebaseui-web), or, if your database is in test, give a try with "public" rules, like:
{
"rules": {
".read": true,
".write": true
}
}

Related

Datatables Bootstrap4 - Uncaught (in promise) Cannot extend unknown button type: create

I have a requirement to display a table, with all CRUD operations.
I am using DataTables for the first time. I have gone through so many post but people have used PHP, and I have no idea about PHP. I am just simply using Datatables with JS.
Please tell me If I am going in any wrong direction.
Anyway, here is the error I am getting.
My code is working fine, I am able to fetch Data. But I want to use inbuilt edit delete feature of Data tables.
Here is my Data table:
$('#table').DataTable(
{
data: userArray,
"lengthMenu": [[5, 10, 15, 20, -1], [5, 10, 15, 20, "All"]],
"pageLength": 10,
select:true,
buttons: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
],
columns: [
{ title: ' User ID' },
{ title: "firstName" },
{ title: 'Last Name' },
{ title: "Email" },
],
});
This is the error:
Uncaught (in promise) Cannot extend unknown button type: create
script-

DataTables when choosing "All" in "Show Entries", No matching records found

Hello i am setting up my first DataTable and i like it very much. Everything works perfect except the All choice in te Show Entries dropdown. It show's nothing when i choose that (No matching records found) The other numbers do work perfectly.
I use this code:
$(document).ready(function(){
$('#empTable').DataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
'processing': true,
'serverSide': true,
'serverMethod': 'post',
'ajax': {
'url':'ajaxfile.php'
},
'columns': [
{ data: 'last_name' },
{ data: 'email' },
{ data: 'gender' },
{ data: 'first_name' },
{ data: 'city' },
],
dom: 'lBfrtip',
buttons: [
'csv', 'excel', 'pdf','print'
],
});
});
Under ajaxfile.php you have used a limit() for limiting the record and that get the values like 25, 50, 100, 200, but for All it value is -1 means the query is like:
.... limit(-1);
That's why it is showing No matching records found.
Make some changes in your logic so that when you get All i.e. -1 as limit parameter, don't use the limit() in that case and fetch all records otherwise use it.
Try this, it will resolve the issue.

How can I decode JSON Unicode using jQuery in a Select2 dropdown filter

I am using Select2 JS and Datatables JS. The data is in JSON format. The data for one value should display as Animal & Veterinary. In JSON it appears as Animal \u0026amp; Veterinary. The Select2 filter displays it as Animal & Veterinary. How can I add a function to the JS below that will decode the Unicode? Below is a function that can work but I dont know how to add it to the JS below.
var title = 'Animal & Veterinary';
function stringToSlug (title) {
return title.toLowerCase().trim()
.replace(/&/g, 'and')
}
Below is the script. This is where I would like to pass the function into the filter. "select2config"
jQuery( document ).ready( function($) {
'use strict';
// Check condition first if the table class exists then run this init.
if ($('.lcds-datatable--advisory-committee-materials').length > 0) {
let pageClass = function () {
let el = $( 'ul.pagination' ).addClass('pagination-sm');
}
// define order of table's control element
let domStyling = "<'row'<'col-sm-12'lB>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>";
var otable9 = $('table.lcds-datatable--advisory-committee-materials').DataTable( {
// Sort of first date column descending.
order: [[0, 'desc']],
deferRender: true,
deferLoading: 50,
dom: domStyling,
ajax: {
"url": "/datatables-json/advisory-committee-materials-json",
//"url": "/sites/default/files/actest1.json",
"dataSrc": ""
},
processing: true,
columns: [
{ "data": "field_publish_date" }, // publish_date 0
{ "data": "title" }, // node title summary 1
{ "data": "field_site_structure" } // site_structure Committee/Topic 2
],
columnDefs: [
{
"type": "date",
"targets": [ 0 ]
}
],
pageLength: 10,
searching: true,
autoWidth: false,
responsive: true,
lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
buttons: [
{
extend: 'excel',
text: 'Export Excel',
exportOptions: {
columns: [ 0, 1, 2 ]
}
}
],
initComplete: pageClass,
drawCallback: pageClass
}); // end datatable
// config and initialize filters
let select2config = {
maximumSelectionLength: 0,
minimumInputLength: 0,
tags: true,
selectOnClose: true,
theme: "bootstrap",
}
let search = $( '#lcds-datatable-filter--search' ).lcdsTableFilter({
table: otable9,
type: 'search'
});
let clear = $( '#lcds-datatable-filter--clear' ).lcdsTableFilter({
table: otable9,
type: 'clear'
});
// wait for ajax call to complete to load column data load
$('table.lcds-datatable--advisory-committee-materials').on( 'init.dt', function() {
let committee = $( '#lcds-datatable-filter--committee-topic' ).lcdsTableFilter({
column: 2,
table: otable9,
select2Options: select2config,
type: 'select',
dataType: 'datatable'
});
})
}}); // end ready function and condition if the table class exists.
I was able to pass in a function to alter the output of JSON so now the filter displays “Animal & Veterinary” not “Animal & Veterinary” By adding this below. The filter now displays Animal & Veterinary but selecting this in the filter does not match the value in the datatable?
let select2config = {
maximumSelectionLength: 0,
minimumInputLength: 0,
tags: true,
selectOnClose: true,
theme: "bootstrap",
escapeMarkup: function (text) { return text; }
}

Jquery Data table export to Excel, Want to convert some number columns to string

This question might have been answered somewhere but I can't get it right yet. I have a data table that I'm exporting to Excel but my problem is the field 'Account Number' has a string like "800953". When I export to excel it's displaying "800,953".
My JS code below seems to be missing something. I had tried to put a dot in front of string then replace it with blank. The bit where it's supposed to pick the first 4 columns is working fine.
"use strict";
$(document).ready(function () {
$('.export-table').DataTable({
fixedHeader: {
header: true
},
dom: 'Bflit',
lengthMenu: [
[100, -1],
['100 rows', 'Show All']
],
buttons: [
{
extend: 'excel',
exportOptions: {
columns: [1, 2, 3, 4],
exportOptions: {
format: {
body: function (data, row, column, node) {
return data.replace(/\./g, ' ');
}
}
}
}
}
]
});
$('.data-table').DataTable({
"lengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]]
});
$('#datable_2').DataTable({ "lengthChange": false });
});
I got solution to my question after going through this thread.
"use strict";
$(document).ready(function () {
$('.export-table').DataTable({
fixedHeader: {
header: true
},
dom: 'Bflit',// 'lBfrtip',// 'Bfrtip',
lengthMenu: [
[100, -1],
['100 rows', 'Show All']
],
buttons: [
{
extend: 'excelHtml5',
customize: function (xlsx) {
var sheet = xlsx.xl.worksheets['sheet1.xml'];
$('row c[r^="C"]', sheet).attr('s', '50'); //"C" is Account number column
}
}
]
});
$('.data-table').DataTable({
"lengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]]
});
$('#datable_2').DataTable({ "lengthChange": false });
});

How to manage datatable for large data

I have a datatable for report. When i tried to show my datas, My browser freezed or crashed. My js code on below
Reporting_Report.DTReport = $('#Report-ReportTable').DataTable({
"ajax": {
"url": "/Ajax/JsonProvider?Method=HardwareHostScreenUsage&GenericObject=true&Json=" + JSON.stringify(json),
"dataSrc": ""
},
"columns": [
{
"data": "BranchName",
"sTitle": "BranchName"
},
{
"data": "HardwareHostFriendlyName",
"sTitle": "Hardware Host Friendly Name"
},
{
"data": "HardwareHostScreenUsageScreenState",
"defaultContent": "N/A",
"sTitle": "Hardware Host Screen Name"
"render": function(data, type, full) {
if (data && Util.Check.IsInteger(data)) {
if (data == 1) {
return "Sorry Screen";
} else if (data == 2) {
return "Welcome Screen";
} else if (data == 3) {
return "Progress Screen";
}
}
}
},
{
"data": "HardwareHostScreenUsageSecondOnScreen",
"sTitle": "Elapsed Time On Hardware Host Screen"
},
{
"data": "HardwareHostScreenUsageRecordDate",
"sTitle": "Hardware Host Screen Usage Record Date"
"render": function (data, type, full) {
return Util.JsonDateToDate(data).format("dd.mm.yyyy HH:MM:ss");
}
}
],
"pageLength": 20,
"lengthMenu": [
[20, 50, 100, -1],
[20, 50, 100, "All"]
],
"info": false,
bFilter: true,
bInfo: false,
"order": [[0, "asc"]],
"scrollX": true,
dom: 'Bfrtip',
buttons: [
{
extend: 'copy'
},
{
extend: 'csv'
},
{
extend: 'excel'
},
{
extend: 'pdf',
title: "Detailed Ticket Report"
message: startDate + " " + startTime + " - " + endDate + " " + endTime + "\t" + datetime,
pageSize: 'LEGAL'
},
{
extend: 'print'
}
]
});
I have more than 100.000 datas.
I thinked maybe i can just get showing page datas and total data number(for manage page numbers) and when clicked another page number send new query and get new datas. But i couldn't find how to do that to.(maybe it cause some another problems (shorting, searching vs.)
Have you got any ideas and solutions.(or this problem has already a solution)
footnote:json has some filters for query(time, branch, etc.)
HardwareHostScreenUsage method gets my datas on c# side.
you can use client side data source also-
var mydata = [];
$('#example').DataTable({
data: data,
deferRender: true,
scrollY: 200,
scrollCollapse: true,
scroller: true
});
fetch all data at once from server and show it while scrolling the table .
You Need these library -
https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js
https://cdn.datatables.net/scroller/1.4.3/js/dataTables.scroller.min.js

Categories