Display jQuery DataTables with Ajax data source in a popup - javascript

I am trying to give a list in a popup according to Ajax request. Before Ajax request , list is in popup but after Ajax request, list stay in the page instead of popup and also there is the old list in the popup window. Here is the codes
<script>
function CreateMap() {
var chart = AmCharts.makeChart("piechartdiv", {
"type": "pie",
"theme": "light",
"fontFamily":"Calibri",
"dataProvider": [{
"product":"Following",
"value": #following,
"color": "#009688"
}, {
"product":"Not Following",
"value": #notFollowing ,
"color": "#555555"
}],
"legend": {
"align" : "right",
"fontSize" : 14
},
"marginLeft":-100,
"marginTop":-45,
"marginBottom":0,
"labelsEnabled":false,
"colorField": "color",
"valueField": "value",
"titleField": "product",
"outlineAlpha": 0.4,
"depth3D": 15,
"balloonText": "[[title]]<br><span style='font-size:14px'><b>[[value]]</b> ([[percents]]%)</span>",
"angle": 20,
"export": {
"enabled": true
}
});
jQuery('.chart-input').off().on('input change', function () {
var property = jQuery(this).data('property');
var target = chart;
var value = Number(this.value);
chart.startDuration = 0;
if (property == 'innerRadius') {
value += "%";
}
target[property] = value;
chart.validateNow();
});
chart.addListener("clickSlice", function (event) {
if ( event.dataItem.title == 'Unfollowing')
{
document.getElementById("s_open").click();
}
});
}
var isAjax = #isAjax;
if(isAjax)
{
CreateMap();
}
else
{
AmCharts.ready(function () {
CreateMap();
});
}
}
<button id="s_open" class="s_open btn-default" style="display:none;">Open popup</button>
<div id="s_follow">
<div class="row" style="border-radius:5px; padding:20px; background-color:#fff;">
<table id="hostTable" class="table table-striped" cellspacing="0">
<thead>
<tr>
<th>Host Table</th>
</tr>
</thead>
<tbody>
#Html.Raw(comparedDataTable.ToString())
</tbody>
</table>
<button class="btn s_close btn-danger">Close</button>
</div>
<script>
$(document).ready(function () {
$('#hostTable').DataTable( {
dom: 'Bfrtip',
buttons: [
'excelHtml5',
'csvHtml5'
],
destroy: true,
} );
});
$(document).ready(function () {
// Initialize the plugin
$('#s_follow').popup({
color: 'black',
opacity: 0.5,
transition: '0.3s',
scrolllock: true
});
});
How can we put the list hostTable into popup after ajax request?

SOLUTION
Use onopen option to initialize the table, see the code below.
$(document).ready(function () {
$('#s_follow').popup({
color: 'black',
opacity: 0.5,
transition: '0.3s',
scrolllock: true,
vertical: "top",
onopen: function() {
// If table was initialized before
if ($.fn.DataTable.isDataTable('#hostTable')){
// Clear table
$('#hostTable').DataTable().clear();
}
$('#hostTable').DataTable( {
dom: 'Bfrtip',
buttons: [
'excelHtml5',
'csvHtml5'
],
destroy: true
});
}
});
});
DEMO
See this jsFiddle for code and demonstration.

Related

Tabulator are not working on Midone template

I imported my tabulator.js from template using webpack.min.js I added .js("resources/js/tabulator.js", "dist/js") to my webpack.min.js, and run npm run dev
then I imported my <script src="{{ asset('dist/js/tabulator.js') }}"></script> bellow <script src="{{ asset('dist/js/app.js') }}"></script>
but as soon I imported it, i got errors <script src="{{ asset('dist/js/tabulator.js') }}"></script> from both app.js and tabulator.js but i kept going since it was working just fine
but then i notice my filters are not working, when i try to type on console table.setFilter() or table.download() it isn't working. below is my js
if ($("#role-tabulator").length) {
// Setup Tabulator
let table = new Tabulator("#role-tabulator", {
ajaxURL: "/role",
ajaxFiltering: true,
ajaxSorting: true,
printAsHtml: true,
printStyled: true,
pagination: "remote",
paginationSize: 10,
paginationSizeSelector: [10, 20, 30, 40, 50],
layout: "fitColumns",
responsiveLayout: "collapse",
placeholder: "No matching records found",
columns: [
{
formatter: "responsiveCollapse",
width: 40,
minWidth: 30,
hozAlign: "center",
resizable: false,
headerSort: false,
},
// For HTML table
{
title: "NAME",
minWidth: 200,
responsive: 0,
field: "name",
vertAlign: "middle",
print: false,
download: false,
formatter(cell, formatterParams) {
return `<div>
<div class="font-medium whitespace-nowrap">${
cell.getData().name
}</div>
</div>`;
},
},{
title: "ACTIONS",
minWidth: 200,
field: "actions",
responsive: 1,
hozAlign: "center",
vertAlign: "middle",
print: false,
download: false,
formatter(cell, formatterParams) {
let a =
$(`<div class="flex lg:justify-center items-center">
<a class="edit flex items-center mr-3" href="javascript:;">
<i data-lucide="check-square" class="w-4 h-4 mr-1"></i> Edit
</a>
<a class="delete flex items-center text-danger" href="javascript:;">
<i data-lucide="trash-2" class="w-4 h-4 mr-1"></i> Delete
</a>
</div>`);
$(a)
.find(".edit")
.on("click", function () {
alert("EDIT");
});
$(a)
.find(".delete")
.on("click", function () {
alert("DELETE");
});
return a[0];
},
},
// For print format
{
title: "NAME",
field: "name",
visible: false,
print: true,
download: true,
},
],
renderComplete() {
createIcons({
icons,
"stroke-width": 1.5,
nameAttr: "data-lucide",
});
},
});
// Redraw table onresize
window.addEventListener("resize", () => {
table.redraw();
createIcons({
icons,
"stroke-width": 1.5,
nameAttr: "data-lucide",
});
});
// Filter function
function filterHTMLForm() {
let field = $("#role-tabulator-html-filter-field").val();
let type = $("#role-tabulator-html-filter-type").val();
let value = $("#role-tabulator-html-filter-value").val();
table.setFilter(field, type, value);
}
// On submit filter form
$("#role-tabulator-html-filter-form")[0].addEventListener(
"keypress",
function (event) {
let keycode = event.keyCode ? event.keyCode : event.which;
if (keycode == "13") {
event.preventDefault();
filterHTMLForm();
}
}
);
// On click go button
$("#role-tabulator-html-filter-go").on("click", function (event) {
filterHTMLForm();
});
// On reset filter form
$("#role-tabulator-html-filter-reset").on("click", function (event) {
$("#role-tabulator-html-filter-field").val("name");
$("#role-tabulator-html-filter-type").val("like");
$("#role-tabulator-html-filter-value").val("");
filterHTMLForm();
});
// Export
$("#role-tabulator-export-csv").on("click", function (event) {
table.download("csv", "data.csv");
});
$("#role-tabulator-export-json").on("click", function (event) {
table.download("json", "data.json");
});
$("#role-tabulator-export-xlsx").on("click", function (event) {
window.XLSX = xlsx;
table.download("xlsx", "data.xlsx", {
sheetName: "Products",
});
});
$("#role-tabulator-export-html").on("click", function (event) {
table.download("html", "data.html", {
style: true,
});
});
// Print
$("#role-tabulator-print").on("click", function (event) {
table.print();
});
}

Datatables server side adding column with parameter

I've a problem when using datatables serverside adding column with parameter. when create datatables serverside without additional column (just query list form database) it is works fine.
But i've difficulty when I want add one column that has value ID.
My script (JS) :
var dataTable = $('#mytablex').DataTable( {
"processing": true,
"serverSide": true,
"ajax":{
url :"<?php echo base_url();?>admin/ap_invoice/getPOs", // json datasource
type: "post", // method , by default get
"data": {
"posupplier_id": $('#vendor_id').val()
},
error: function(){ // error handling
$(".employee-grid-error").html("");
$("#mytablex").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
}
},
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<input type='checkbox' id='supid[]' name='supid[]'>"
} ]
} );
when i'm adding
<input type='checkbox' id='supid[]' name='supid[]'>
how to fill with value each rowid , i want become like this
<input type='checkbox' id='supid[]' name='supid[]' value='row->po_id'>
or you can use select ext.
$(document).ready(function () {
var events = $('#events');
var table = $('#example').DataTable({
//you can change data to ajax, there is an example
data: [{
"id": 1,
"name": "datatables",
"position": "anywhere",
"office": "stackoverflow",
"age": 18,
"salary": 341
}],
dom: 'Bfrtip',
columns: [
{
"data": "id"
},
{
"data": "name"
},
{
"data": "position"
},
{
"data": "office"
},
{
"data": "age"
},
{
"data": "salary"
}
],
columnDefs: [{
orderable: false,
className: 'select-checkbox',
targets: 0
}],
select: {
style: 'os',
selector: 'td:first-child'
},
order: [[1, 'asc']],
buttons: [
{
text: 'Get selected data',
action: function () {
var count = table.rows({
selected: true
}).count();
events.prepend('<div>' + count + ' row(s) selected</div>');
var data = table.rows({
selected: true
}).data().toArray();
//print whole row data
console.log(data);
//print id
console.log(data[0].id);
}
}
]
});
});
#events {
margin-bottom: 1em;
padding: 1em;
background-color: #f6f6f6;
border: 1px solid #999;
border-radius: 3px;
height: 100px;
overflow: auto;
}
<link href="https://cdn.datatables.net/select/1.3.0/css/select.dataTables.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/select/1.3.0/js/dataTables.select.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.6/js/dataTables.buttons.min.js"></script>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Unable to convert HTML to Javascript Variable

I'm trying to nest a jQuery DataTable in a main DataTable. I am able to create the child table and populate it, but when I try and copy the HTML into a JavaScript function that shows the nested row, I get an error since the HTML has line breaks, extra spaces and is not wrapped in quotes.
How can I get this to work?
<link rel="stylesheet" type="text/css" href="/css/dataTables.jqueryui.css" />
<script type="text/javascript" charset="utf8" src="/scripts/jquery.dataTables.min.js"></script>
<script type="text/javascript" charset="utf8" src="/Scripts/dataTables.jqueryui.js"></script>
<script type="text/javascript" charset="utf8" src="/scripts/tinymce/tiny_mce.js"></script>
<style type="text/css">
#ethicsOpinions_wrapper select {
width: auto;
}
.ui-dialog-content.ui-widget-content {
padding: 10px 30px 10px 15px;
}
td.details-control {
background: url('/images/details_open.png') no-repeat center center;
cursor: pointer;
}
tr.shown td.details-control {
background: url('/images/details_close.png') no-repeat center center;
}
</style>
<script type="text/javascript">
var ethicalRulesTableHtml;
$(function () {
ethicalRulesTableHtml = $("#ethicalRulesGrid").html();
var table = $('#ethicalRulesSections').DataTable({
"ajax": "/umbraco/surface/RulesSurface/getRulesSections",
"order": [[1, 'asc']],
stateSave: false,
"paging": false,
"autoWidth": true,
"processing": true,
"jQueryUI": true,
"destroy": true,
"deferRender": true,
"filter": false,
"dom": '<lfr>t<"F"p>',
"columns": [
{
"data": null,
className: "dt-center details-control",
"defaultContent": "",
"width": "20px",
"orderable": false
},
{
"data": 0,
"visible": false
},
{
"data": 1,
"width": "50px",
className: "dt-center"
},
{
"data": 2
}
]
});
// Add event listener for opening and closing details
$('#ethicalRulesSections tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child("'" + format(row.data()) + "'").show();
tr.addClass('shown');
}
});
});
function format(d) {
$('#ethicalRules').DataTable({
"ajax": "/umbraco/surface/RulesSurface/getRules/" + d[0],
"order": [[1, 'asc']],
"width": "630px",
stateSave: false,
"paging": false,
"autoWidth": true,
"processing": true,
"jQueryUI": true,
"destroy": true,
"deferRender": true,
"filter": false,
"dom": '<lfr>t<"F"p>',
"columns": [
{
"data": 1,
"visible": false
},
{
"data": 2,
"width": "50px",
className: "dt-center"
},
{
"data": 3
}
],
"initComplete": function (settings, json) { return $('#ethicalRules')[0].outerHTML; }
});
}
</script>
<div id="ethicalRulesSectionsGrid">
<table id="ethicalRulesSections" cellpadding="0" cellspacing="0" border="0" class="display ca_highlight_row">
<thead>
<tr>
<th></th>
<th></th>
<th>Section Number</th>
<th>Section</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div id="ethicalRulesGrid">
<table id="ethicalRules" cellpadding="0" cellspacing="0" border="0" class="display ca_highlight_row" style="margin:0 0 0 110px;">
<thead>
<tr>
<th></th>
<th>Rule Number</th>
<th>Rule</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
Basically the solution is to clone your child table HTML template, add a new child row using HTML content of the cloned element, locate the added table and create a DataTables object based on that.
You need to remove id attribute form your child table as shown below and make its container initially hidden.
HTML
I have omitted some of your HTML code, only child table is shown below.
<div id="ethicalRulesGrid" style="display:none">
<table cellpadding="0" cellspacing="0" border="0" class="display ca_highlight_row" style="margin:0 0 0 110px;">
<thead>
<tr>
<th></th>
<th>Rule Number</th>
<th>Rule</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
JavaScript
var ethicalRulesTableHtml;
$(function () {
ethicalRulesTableHtml = $("#ethicalRulesGrid").html();
var table = $('#ethicalRulesSections').DataTable({
"ajax": "/umbraco/surface/RulesSurface/getRulesSections",
"order": [[1, 'asc']],
stateSave: false,
"paging": false,
"autoWidth": true,
"processing": true,
"jQueryUI": true,
"destroy": true,
"deferRender": true,
"filter": false,
"dom": '<lfr>t<"F"p>',
"columns": [
{
"data": null,
className: "dt-center details-control",
"defaultContent": "",
"width": "20px",
"orderable": false
},
{
"data": 0,
"visible": false
},
{
"data": 1,
"width": "50px",
className: "dt-center"
},
{
"data": 2
}
]
});
// Add event listener for opening and closing details
$('#ethicalRulesSections tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
// Destroy child table
tr.next().find('table').DataTable().destroy();
// This row is already open - close it
row.child.remove();
tr.removeClass('shown');
}
else {
// Open this row
format(table, tr);
}
});
});
function format(table, tr) {
var row = table.row(tr);
var d = row.data();
tr.addClass('shown');
// Clone child table and insert it as child row
row.child($('#ethicalRulesGrid').clone().html()).show();
// Locate child table
var $child_table = tr.next().find('table');
// Initialize child table
$child_table.DataTable({
"ajax": "/umbraco/surface/RulesSurface/getRules/" + d[0],
"order": [[1, 'asc']],
"width": "630px",
"stateSave": false,
"paging": false,
"autoWidth": true,
"processing": true,
"jQueryUI": true,
"destroy": true,
"deferRender": true,
"filter": false,
"dom": '<lfr>t<"F"p>',
"columns": [
{
"data": 1,
"visible": false
},
{
"data": 2,
"width": "50px",
className: "dt-center"
},
{
"data": 3
}
]
});
}

Reload dataTables after button click

I'm sure there are a few (better) ways to do this, but I can't get any way to work. I'm trying to have datatables load new data (from different data source) when a button is clicked.
Here's what I have:
$(document).ready(function() {
$('#datatable2').dataTable( {
"ajax": {
"url":"simple4.php",
"type":"GET"
} ,
"paging": true,
"pageLength": 20,
"order": [[ 2, "asc" ]],
"aoColumns": [
{ "bSortable": false, "width": "25%" },
{ "bSortable": true, "width": "30%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": false, "width": "0%", "visible":false },
],
});
$( "#option2" ).click(function() {
table.ajax.url( 'simple3.php' ).load();
});
});
The initial table (from simple4.php) loads fine. I'd like it to change when I click on a button (with id=option2 in this case), but nothing happens when I click the button.
Just in case, here's the button code in case I'm missing something obvious:
<label class="btn btn-default">
<input type="radio" name="options" id="option2" value="1" autocomplete="off"> Compare 1 and 2
</label>
Not sure what the issue is. Any insight would be helpful.
UPDATE: see answers below explanation of the issue. One thing I didn't do, which apparently makes a major difference is using "dataTable" versus "DataTable". You need a capital D and capital T. Here's the fixed code that's working now:
$(document).ready(function() {
var table = $("#datatable2").DataTable({
"ajax": {
"url":"simple3.php",
"type":"GET"
} ,
"paging": true,
"pageLength": 20,
"order": [[ 2, "asc" ]],
"aoColumns": [
{ "bSortable": false, "width": "25%" },
{ "bSortable": true, "width": "30%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": true, "width": "15%" },
{ "bSortable": false, "width": "0%", "visible":false },
],
});
$( "#option2" ).click(function() {
table.ajax.url( "simple4.php" ).load();
});
});
One more thing...my function that was supposed to fire when I clicked on my radio button wasn't working. Had to change from this:
$( "#option2" ).click(function() {
table.ajax.url( "simple4.php" ).load();
});
To this:
$('input[id=option2]').change(function(){
table.ajax.url( "simple4.php" ).load();
});
First, as the others have said the variable 'table' is not set.
Second, when you call
var table = $('#datatable2').dataTable({.....})
You are returning a jQuery object that won't have access to any of the DataTables API
To get a DataTables API instance you need to make a call like this:
var table = $('#datatable2').DataTable({....});
This should work, assuming that your data returned by your url is properly formed.
Source: https://datatables.net/faqs/#api
I can't try this now, but I think it gonna work:
var table = $('#datatable2').dataTable({...});
$( "#option2" ).click(function() {
table.ajax.url( 'simple3.php' ).load();
});
you are not setting var table = ... so when you call table.ajax... table var does not exists

JQuery UI - Form doesn't open if autoOpen: false

I am using JQuery UI and I have a dialog box that I want to appear when a button is clicked. When autoOpen is set to true, it will display as soon as page loads and it will open and close. If it is set to false it will not open at all.
The JQuery UI code is at the bottom of this code block
$(document).ready(function () {
retrieveNotes().done(function (data) {
$.each(data.d, function (i, item) {
DataArray[i] = [];
DataArray[i][0] = item.NotesID.trim();
DataArray[i][1] = item.NotesTitle.trim();
DataArray[i][2] = item.NotesText.trim();
DataArray[i][3] = item.ProfileName.trim();
DataArray[i][4] = item.IsShared;
DataArray[i][5] = item.NameOfUser.trim();
});
// GRID LOGIC HERE
var tbl = $("#notes_table");
var obj = $.paramquery.tableToArray(tbl);
var newObj = {
width: 720, height: 300, sortIndx: 0,
editable: false,
flexHeight: false,
title: "Here are your notes for this profile</b>",
freezeCols: 1, resizable: false, selectionModel: { type: 'row' }, editModel: { clicksToEdit: 2 },
selectionModel: { mode: 'single' }
};
// MUST DECLARE CORRECT NUMBER OF COL PROPERTIES OTHERWISE NULL REFERENCE
obj.colModel = [
{ title: "Note ID", width: 50, dataType: "string" },
{ title: "Note Title", width: 255, dataType: "string" },
{ title: "Note Text", width: 255, dataType: "string" },
{ title: "Name of Profile", width: 200, dataType: "string" },
{ title: "Is Shared Profile", width: 10, dataType: "boolean" },
{ title: "Note created by:", width: 255, dataType: "string" },
];
newObj.dataModel = { data: DataArray, paging: "local", rPP: 15, rPPOptions: [10, 15, 20, 50, 100] };
newObj.colModel = obj.colModel;
//Hide GUID column from user but have it on DOM for edit/delete commands
newObj.colModel[0].hidden = true;
newObj.colModel[1].width = 255;
newObj.colModel[2].hidden = true;
newObj.colModel[3].width = 200;
newObj.colModel[4].width = 10;
newObj.colModel[5].width = 255;
//append or prepend the CRUD toolbar to .pq-grid-top or .pq-grid-bottom
$("#divGrid").on("pqgridrender", function (evt, obj) {
var $toolbar = $("<div class='pq-grid-toolbar pq-grid-toolbar-crud'></div>").appendTo($(".pq-grid-top", this));
$("<span>Add</span>").appendTo($toolbar).button({ icons: { primary: "ui-icon-circle-plus" } }).click(function (evt) {
addRow();
});
$("<span>Edit</span>").appendTo($toolbar).button({ icons: { primary: "ui-icon-pencil" } }).click(function (evt) {
editRow();
});
$("<span>Delete</span>").appendTo($toolbar).button({ icons: { primary: "ui-icon-circle-minus" } }).click(function () {
deleteRow();
});
$toolbar.disableSelection();
});
$grid = $("#divGrid").pqGrid(newObj);
//create popup dialog.
$("#popup-dialog-crud").dialog({
width: 400, modal: true,
open: function () { $(".ui-dialog").position({ of: "#divGrid" }); },
autoOpen: false
});
//buildGrid(DataArray);
});
});
My HTML
<div id="popup-dialog-crud" style="width: auto; min-height: 47px; height: auto;" class="ui-dialog-content ui-widget-content" scrolltop="0" scrollleft="0">
<form id="crud-form">
<table align="center">
<tbody>
<tr>
<td class="label">Company Name:</td>
<td>
<input type="text" name="company"></td>
</tr>
<tr>
<td class="label">Symbol:</td>
<td>
<input type="text" name="symbol"></td>
</tr>
<tr>
<td class="label">Price:</td>
<td>
<input type="text" name="price"></td>
</tr>
<tr>
<td class="label">Change:</td>
<td>
<input type="text" name="change"></td>
</tr>
<tr>
<td class="label">%Change:</td>
<td>
<input type="text" name="pchange"></td>
</tr>
<tr>
<td class="label">Volume:</td>
<td>
<input type="text" name="volume"></td>
</tr>
</tbody>
</table>
</form>
</div>
You can simply do this:
$( "#opener" ).click(function() {
$( "#popup-dialog-crud" ).dialog( "open" );
});
FIDDLE DEMO

Categories