Refresh Gridjs Table on AJAX success - javascript

The AJAX code works fine and creates my desired outputs and on "success"
success: function (data) {
console.log(data);
$( "#gridjs_table" ).load(window.location.href + " #gridjs_table" );//updates the gridjs_table div
}
Gridjs Table works fine as well
<script src="https://cdn.jsdelivr.net/npm/gridjs/dist/gridjs.umd.js"></script>
<link href="https://cdn.jsdelivr.net/npm/gridjs/dist/theme/mermaid.min.css" rel="stylesheet"/>
<div id="gridjs_table">
<div id="wrapper"></div>
<script>
new gridjs.Grid({
columns: [
{ name: "Title",
formatter: (cell, row) => {
return gridjs.html(`<span style='text-align: center;' id='visible_title'>${row.cells[0].data}</span>`);
}},
{ name: "src", hidden: true},
{ name: "Cover",
sort:{enabled: false},
formatter: (cell, row) => {
return gridjs.html(`<div style='text-align: center;'><img id="cover" src="../library/${row.cells[1].data}" alt="no"></div>`);
}
},
{ name: "Link", sort:{enabled: false},
formatter: (cell, row) => {
return gridjs.html(`<div id='link_format'><span id='visible_link'>${row.cells[3].data}</span><br><a href='${row.cells[3].data}' target='_blank'><div id='visit'>Visit</div></a></div>`);
}},
{ name: "Status"},
{ name: "Views"},
{ name: "Stars" },
{ name: "Bookmarked"},
{ name: "Action",
sort:{enabled: false},
formatter: (cell, row) => {
return gridjs.html(`<a href='edit.php?file=${row.cells[2].data}' onclick="window.open('edit.php?file=${row.cells[2].data}',
'newwindow',
'width=300,height=250');
return false;"><div id='edit'>Edit</div></a>
<a href='../library/view.php?view=${row.cells[2].data}' onclick="window.open('../library/view.php?view=${row.cells[2].data}',
'newwindow',
'width=320,height=580');
return false;" target='_blank'><div id='mobile'>Mobile</div></a>
`);
}
}
],
data: [
<?php
echo $data_implode;
?>
],
sort: true,
search: {
enabled: true,
debounceTimeout: 500,
},
style: {
table: {
border: '3px solid #ccc',
},
},
fixedHeader: true,
pagination: {
enabled: true,
limit: 3
}
}).render(document.getElementById("wrapper"));
</script>
</div>
</div>
On success, the ajax should refresh the table but it's not working. It just went blank, no display, the whole table is gone. Refreshing the whole page works and displays the newly added items but I don't want that.

Refreshing the div holding the table does not work so I ended up using this code and it worked.
$('body').load('dashboard.php');

Related

DataTables sorting for category name column doesn't work

Here is HTML code
<table id="datatable-language" class="table table-hover datatable-highlight">
<thead>
<tr>
<th></th>
<th>image</th>
<th>category_name</th>
<th>status</th>
<th></th>
<th></th>
</tr>
</thead>
</table>
Here is the JS code inside Datatable
columns: [
{
title: `<input type="checkbox" class="styled" onchange='toggleSelectAll(this);'>`,
orderable: false,
data: "category_id",
width: "50px"
},
{
data: "image",
render: function (data, type, row) {
return `<img src="${row['image']}" height="50px">`;
},
width: "100px"
},
{
data: "name",
ordering: true,
render: function (data, type, row) {
return `${row['name']}`;
}
},
{
data: "cstatus",
width: "30px"
},
{
width: "30px",
data: "category_id"
},
{
width: "10px",
data: "category_id"
},
],
columnDefs: [
{
targets: 1,
orderable: true
},
{
targets: 2,
orderable: true
},
{
orderable: false,
className: 'select-checkbox',
targets: 0
},
{
targets: 3,
render: function (data, type, row) {
var status = (data == "1" ? 'checked="checked"' : '');
return statusSwitch(row.category_id, status);
}
},
{
targets: 4,
orderable: false,
selectable: false,
visible: true,
render: function (data, type, row) {
return `<a data-popup="tooltip" title="${locales['text_preview']}" target="_blank" href="{{ linkfront('product/category', 'path=') }}${row['category_id']}" class='text-default'><i class='fa fa-eye fa-lg valign-middle'></i></a>`;
}
},
{
targets: 5,
orderable: false,
render: function (data, type, row) {
return `<ul class="icons-list pull-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-menu9"></i>
</a>
<ul class="dropdown-menu dropdown-menu-right">
<li><a href='{{ link('catalog/category/update') }}?category_id=${row['category_id']}'><i class='icon-pencil7'></i> ${locales['button_edit']}</a></li>
<li><a onclick="removeItem(${row['category_id']})"><i class='icon-trash'></i> ${locales['button_delete']}</a></li>
</ul>
</li>
</ul>
`;
}
}
]
As you see, I make the orderable attr to true and the category_name still not working. Is there's a missing property of config?!
so what is the problem? the rest of the code doesn't make sense at all. I attached the snippets that make the table configurations
{
data: "name",
ordering: true,
render: function (data, type, row) {
return `${row['name']};
}
you write this
change data:"name" to data:"category_name"
and also return
${row['name']};
here change name to category_name
Take a look at the columns.render docs > https://datatables.net/reference/option/columns.render, especially the type param.
Your problem is that DT will sort the columns rendered markup, not the name value itself. So pass back the name value for sorting, markup for everything else:
render: function (data, type, row) {
return type == 'sort'
? row['name']
: `${row['name']};
}

Hide a button in jquery based on user access

I'm trying to hide a button. If it was on the html i would simply do
<security:authorize access="hasAuthority('Administrator')">
//html button code
</security:authorize>
but my delete button is being generated from datatable.
var table = $('#dataTable').DataTable({
language: {
searchPlaceholder: "Search...",
emptyTable: "There are no available flows."
},
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
targets: 0
},
{type: "date-euro", targets: 7},
{type: "date-euro", targets: 8}
],
order: [[1, 'desc']],
select: {
style: 'multi',
selector: 'td:first-child'
},
lengthChange: false,
dom: 'Bfrtip',
buttons: [
{
text: '<span class="fa fa-plus"></span> Create',
className: 'btn-primary-outline',
action: function () {
location.href = "create-flow";
}
},
{
text: '<span class="fa fa-trash"></span> Delete',
className: 'btn-danger-outline',
action: function () {
console.log($('#hasAuthority').val());
var selectedRows = table.rows({selected: true});
if (selectedRows.nodes().length > 0) {
//Get names
var data = selectedRows.data();
var names = [];
$.each(data, function (index, value) {
names.push(value[2]);
});
//Remove them
$.ajax({
url: '/flow/delete?names=' + names,
type: 'delete',
success: function () {
//reload page
location.reload();
}
});
//de-select selected rows
table.rows('.selected').deselect();
}
}
}
]
});
I'm trying to give a value to a input if user is admin or not but I'm getting undefined
<security:authorize access="hasAuthority('Administrator')" var="hasAuthority"></security:authorize>
<input type="hidden" id="hasAuthority" value="${hasAuthority}">
But then how do I corporate the if(hasAuthority) only on the delete button? The syntax doesn't match.

Enabling Save button on JQ Grid with InlineEditing and CellEdit

Hi I have a Grid that is using cell edit and Inline editing. It saves to the ClientArray
$('#list').jqGrid({
datatype: "local",
colNames: ["Parameter Id", "Parameter Name", 'Parameter Value'],
colModel: [
{ name: "Id", index: "Id", align: "left", key: true, editable: false,hidden:true, jmap: 0 },
{ name: "ParameterName", index: "ParameterName", align: "left", editable: false, jmap: 1 },
{ name: "ParameterValue", index: "ParameterValue", align: "left", editable: true, edittype: "text", editoptions: { maxlength: 100 }, editrules: {required: true }, jmap: 2 }
],
pager: "#pager",
rowNum: 100,
rowList: [],
pgbuttons: false, // disable page control like next, back button
pgtext: null, // disable pager text like 'Page 0 of 10'
viewrecords: true, // disable current view record text like 'View 1-10 of 100'
height: '100%',
scrollOffset: 0,
sortname: "Name",
sortorder: "Asc",
gridview: true,
caption: 'Parameters',
autowidth: true,
hidegrid: false,
loadonce: true,
//beforeEditCell: function () {
// $("#list_ilsave").removeClass('ui-state-disabled');
// return;
//},
//afterEditCell: function (rowid, cellname, value, iRow, iCol) {
// $('#list').jqGrid('getCell', rowid, iCol).focus();
// return;
//},
width: totalWidth,
cellEdit: true,
cellsubmit: "clientArray"
});
$('#list').jqGrid('inlineNav', '#pager', {
edit: false,
add: false,
del: false,
save: true,
savetext: 'Save',
cancel: false
});
When I edit a Cell the save button remains disabled. If I manually Enable the button in beforeCellEdit, the editable cell hasn't got focus until you select another cell. This behavior is only happening in IE.
I have tried to fix both these issues individually in my commented out code, and I have found that the loss of focus is caused by the line
$("#list_ilsave").removeClass('ui-state-disabled');
I tried placing this line in beforeEditCell and in afterEditCell and it causes the input field to loose focus.
I was using JQ Grid 4.4.4 and I have tried updating to 4.6.0 after I read there were updates to Inline Editing after 4.4.4
UPDATE
I have changed my grid to use onSelectRow
onSelectRow: function (rowid) {
var $grid = $('#list');
var iRow = $("#" + rowid)[0].rowIndex;
$grid.jqGrid('editRow', rowid, {
keys: true,
oneditfunc: function(rowid, response) {
var $saveButton = $("#list_ilsave");
if ($saveButton.hasClass('ui-state-disabled')) {
$saveButton.removeClass('ui-state-disabled');
}
markCellAsDirty(rowid, $grid);
return true;
},
successfunc: function() {
alert('success');
return true;
},
aftersavefunc: function() {
alert('after save');
return true;
},
errorfunc: function() {
alert('error');
return true;
}
});
},
cellsubmit: "clientArray"
But I can't get any of the editRow events to fire other than oneditfunc. I also have an issue with getting the changed cells.
This method marks the cells as dirty / edited
function markCellAsDirty(rowid, grid) {
$(grid.jqGrid("setCell", rowid, "ParameterValue", "", "dirty-cell"));
$(grid[0].rows.namedItem(rowid)).addClass("edited");
}
I try to get the edited cells as follows
var editedRows = $grid.getChangedCells('dirty');
Before posting editedRows in an AJAX method to my server.
I'm not sure what you want to implement exactly, but I modified your demo to the following https://jsfiddle.net/OlegKi/byygepy3/11/. I include the full JavaScript code of the demo below
$(function () {
var myData = [
{ id: 10, ParameterName: "Test", ParameterValue: "" },
{ id: 20, ParameterName: "Test 1", ParameterValue: "" },
{ id: 30, ParameterName: "Test 2", ParameterValue: "" }
],
$grid = $("#list");
// change the text displayed on editrules: {required: true }
$.extend(true, $.jgrid.locales["en-US"].edit.msg, {
required: "No value was entered for this parameter!!!"
});
$grid.jqGrid({
datatype: "local",
data: myData,
colNames: ["", "Parameter Name", "Parameter Value"],
colModel: [
{ name: "act", template: "actions" }, // optional feature
{ name: "ParameterName" },
{ name: "ParameterValue", editable: true,
editoptions: { maxlength: 100 }, editrules: {required: true } }
],
cmTemplate: { autoResizable: true },
autoResizing: { compact: true },
pager: true,
pgbuttons: false, // disable page control like next, back button
pgtext: null, // disable pager text like 'Page 0 of 10'
viewrecords: true, // disable current view record text like 'View 1-10 of 100'
sortname: "Name",
iconSet: "fontAwesome",
caption: 'Parameters',
autowidth: true,
hidegrid: false,
inlineEditing: {
keys: true
},
singleSelectClickMode: "selectonly", // prevent unselect once selected rows
beforeSelectRow: function (rowid) {
var $self = $(this), i,
// savedRows array is not empty if some row is in inline editing mode
savedRows = $self.jqGrid("getGridParam", "savedRow");
for (i = 0; i < savedRows.length; i++) {
if (savedRows[i].id !== rowid) {
// save currently editing row
// one can replace saveRow to restoreRow in the next line
$self.jqGrid("saveRow", savedRows[i].id);
}
}
return savedRows.length === 0; // allow selection if saving successful
},
onSelectRow: function (rowid) {
$(this).jqGrid("editRow", rowid);
},
afterSetRow: function (options) {
var item = $(this).jqGrid("getLocalRow", options.rowid);
if (item != null) {
item.dirty = true;
}
},
navOptions: {
edit: false,
add: false,
search: false,
deltext: "Delete",
refreshtext: "Refresh"
},
inlineNavOptions: {
save: true,
savetext: "Save",
cancel: false,
restoreAfterSelect: false
},
formDeleting: {
// delete options
url: window.g_baseUrl + 'MfgTransactions_MVC/COA/Delete?',
beforeSubmit: function () {
// get value
var selRowId = $(this).jqGrid('getGridParam', 'selrow');
var parametricValue = $(this).jqGrid('getCell', selRowId, 'ParameterValue');
// check if empty
if (parametricValue === "") {
return [false, "Cannot delete: No value exists for this parameter"];
}
return [true, "Successfully deleted"];
},
delData: {
batchId: function () {
return $("#BatchId").val();
}
},
closeOnEscape: true,
closeAfterDelete: true,
width: 400,
msg: "Are you sure you want to delete the Parameter?",
afterComplete: function (response) {
if (response.responseText) {
alert("response.responseText");
}
//loadBatchListIntoGrid();
}
}
}).jqGrid('navGrid')
.jqGrid('inlineNav')
.jqGrid('navButtonAdd', {
caption: "Save Changed",
buttonicon: "fa-floppy-o",
onClickButton: function () {
var localData = $(this).jqGrid("getGridParam", "data"),
dirtyData = $.grep(localData, function (item) {
return item.dirty;
});
alert(dirtyData.length > 0 ? JSON.stringify(dirtyData) : "no dirty data");
}
});
// make more place for navigator buttons be rwducing the width of the right part
var pagerIdSelector = $grid.jqGrid("getGridParam", "pager");
$(pagerIdSelector + "_right").width(100);
// make the grid responsive
$(window).bind("resize", function () {
$grid.jqGrid("setGridWidth", $grid.closest(".container-fluid").width());
}).triggerHandler("resize");
});
where HTML code is
<div class="container-fluid">
<div class="row">
<div id="gridarea" class="col-md-6 col-md-offset-3">
<table id="list"></table>
</div>
</div>
</div>
and CSS code
.ui-th-column>div, .ui-jqgrid-btable .jqgrow>td {
word-wrap: break-word; /* IE 5.5+ and CSS3 */
white-space: pre-wrap; /* CSS3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
overflow: hidden;
vertical-align: middle;
}
It demonstrate how one can implement starting inline editing on select row. Additionally I added optional column with template: "actions" which can be alternative implementation. I set property dirty in every item of data inside of afterSetRow callback and I added "Save Changed" button, which uses localData = $(this).jqGrid("getGridParam", "data") and dirtyData = $.grep(localData, function (item) { return item.dirty; }); to get the dirty (modified) data.

DataTables API row().data()

Hi everybody and happy new year :)
So, I use dataTables library. In their web site i found this example, where function must return the row of table, which was clicked.
var table = $('#example').DataTable();
$('#example tbody').on( 'click', 'tr', function () {
console.log( table.row( this ).data() );
} );
I try use this example for my code, but i have the error
Uncaught TypeError: aucTable.row is not a function
my code:
var mainTable = $('#mainTable');
$(document).ready(function () {
mainTable.dataTable({
'searching': false,
'ajax': 'assets/static_data/data.json',
'columns': [
{
title: "Name",
data: "name"
},
{
title: "Office",
data: "office"
},
{
title: "Extn.",
data: "extn"
},
{
title: "Salary",
data: "salary"
},
{
title: "Start date",
data: "start_date"
},
{
title: "Details",
data: null,
defaultContent: "<button class='details-btn btn'>More details</button>",
sorting: false
}
]
});
});
$('#mainTable').on('click', '.details-btn', function () {
var selectedRow = aucTable.row(this).data();
console.log(selectedRow);
$("<div id='details-dialog'/>").dialog({
modal: true,
show: true,
maxWidth: 620,
maxHeight: 300,
minWidth: 500,
minHeight: 200,
title: "Hello World"
});
});
Can somebody tell me, why I have this error? And why i can't get the row, which was clicked?
Tanks for everybody.
Best regard and have fun.
I'm not familiar with datatables, however you might try changing it to the following:
var mainTable = null;
$(document).ready(function () {
mainTable = $('#mainTable').dataTable({...});
});
$('#mainTable').on('click', '.details-btn', function () {
var tr = $(this).closest('tr');
var selectedRow = mainTable.row(tr).data();
console.log(selectedRow);
//...
});
Note that I'm storing the result to the $('#mainTable').dataTable() call in the mainTable variable so that you can reference it later when calling the row() function.
The other thing to note is that in your click handler, it looks like you need to find the tr from the datatable - calling mainTable.row(this) does not yield a row because this is the button that was clicked, not the row of the table.
See this link for an example that seems similar to what you're doing.
In the current code, the acuTable var not exist. So you can change your code in order to have an acuTable var pointing to the datatable instance, something like:
var mainTable = $('#mainTable');
var acuTable;
$(document).ready(function () {
acuTable = mainTable.dataTable({
'searching': false,
'ajax': 'assets/static_data/data.json',
'columns': [
{
title: "Name",
data: "name"
},
{
title: "Office",
data: "office"
},
{
title: "Extn.",
data: "extn"
},
{
title: "Salary",
data: "salary"
},
{
title: "Start date",
data: "start_date"
},
{
title: "Details",
data: null,
defaultContent: "<button class='details-btn btn'>More details</button>",
sorting: false
}
]
});
});
$('#mainTable').on('click', '.details-btn', function () {
var selectedRow = aucTable.row(this).data();
console.log(selectedRow);
$("<div id='details-dialog'/>").dialog({
modal: true,
show: true,
maxWidth: 620,
maxHeight: 300,
minWidth: 500,
minHeight: 200,
title: "Hello World"
});
});

Kendo Grid Row Selection Client-side Persistence Issue

We have selections persisting, maybe just a bit too much. :D
For example, if you have a multipage kendo grid with client side data, do this with a client side kendo grid:
Select a row on Page 1
Go to Page 2
Select a row on Page 2 THEN deselect it and select another row
Go back to Page 1 (row selection persists)
Go back to Page 2
Row selection persists, but also the row that was previously deselected is also selected.
Is there a solution to this? Something we can use in the change event:
http://dojo.telerik.com/#crunchfactory/uhEZe/7
Thank you,
j
Please try with the below code snippet.
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2015.2.902/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2015.2.902/styles/kendo.material.min.css" />
<script src="https://kendo.cdn.telerik.com/2015.2.902/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2015.2.902/js/kendo.all.min.js"></script>
</head>
<body>
<script src="http://demos.telerik.com/kendo-ui/content/shared/js/products.js"></script>
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function () {
var selectedOrders = [];
var idField = "ProductID";
$("#grid").kendoGrid({
dataSource: {
data: products,
schema: {
model: {
fields: {
ProductName: { type: "string" },
UnitPrice: { type: "number" },
UnitsInStock: { type: "number" },
Discontinued: { type: "boolean" }
}
}
},
pageSize: 20
},
height: 550,
scrollable: true,
sortable: true,
selectable: "multiple, row",
pageable: {
input: true,
numeric: false
},
columns: [
"ProductName",
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: "130px" },
{ field: "UnitsInStock", title: "Units In Stock", width: "130px" },
{ field: "Discontinued", width: "130px" }
],
change: function (e, args) {
var grid = e.sender;
var items = grid.items();
items.each(function (idx, row) {
var idValue = grid.dataItem(row).get(idField);
if (row.className.indexOf("k-state-selected") >= 0) {
selectedOrders[idValue] = true;
} else if (selectedOrders[idValue]) {
delete selectedOrders[idValue];
}
});
},
dataBound: function (e) {
var grid = e.sender;
var items = grid.items();
var itemsToSelect = [];
items.each(function (idx, row) {
var dataItem = grid.dataItem(row);
if (selectedOrders[dataItem[idField]]) {
itemsToSelect.push(row);
}
});
e.sender.select(itemsToSelect);
}
});
});
</script>
</div>
</body>
</html>
Let me know if any concern.

Categories