I am trying to give the user the ability to cancel the jQuery DataTable(ver 1.10.8) ajax request by pressing the button,
but all the solutions i have tried are not giving me the required results.
Here is what i have tried :
let table = $('#data-table').DataTable({
destroy: true,
responsive: true,
serverSide: false,
autoWidth: false,
paging: true,
filter: true,
searching: true,
stateSave: true,
scrollX: true,
lengthMenu: [5, 10, 25],
language: {
"search": "Filtrer: "
},
ajax: {
url: '/User/GetUsersByDepartment',
type: 'POST',
data: {
QueryValue: departmentName,
Type: type
},
dataSrc: '',
},
columns: [
{
title: 'Display Name',
data: 'UserName',
},
{
title: 'Date Joined',
data: 'JoinedDate',
}
],
initComplete: function (settings, json) {
HideSpinner();
//Do something with json data;
}
}).order([[1, 'asc']]).draw(false);
//..This function is called upon pressing cancel button
function CancelSearch() {
table.context[0].jqXHR.abort();
HideSpinner();
}
Related
I'm stuck on a portion of my datatable Ajax reload. In the beginning of my javascript file I have the following:
var courtDateSelected;
docketCheckedInDataTable = $('#data-checked-in').DataTable({
ajax: {
type: "POST",
url: base_url + '/courts/dockets/api/list1',
dataType: 'json',
data: {
'court_date_id': courtDateSelected,
'checked_in': 'true',
},
error: function (xhr, error, code)
{
console.log(xhr);
console.log(code);
},
"dataSrc": function (json) {
//Make your callback here.
$('#checkedInCount').html(json.data.length);
return json.data;
}
},
"paging": true,
"dom": '<"datatable-header"f>rt<"datatable-footer"p>',
"ordering": true,
"bLengthChange": false,
"autoWidth": false,
"searching": true,
"info": false,
"order": [],
"columns": [
{data: 'view', name: 'view', orderable: false},
{data: 'docket_number', name: 'docket_number', orderable: false},
{data: 'last_name', name: 'last_name', orderable: true},
{data: 'first_name', name: 'first_name', orderable: false},
{data: 'balance', name: 'balance', orderable: false},
{data: 'actions', name: 'actions', orderable: false},
],
language: {
search: "_INPUT_",
searchPlaceholder: "Search Keywords...",
emptyTable: "There are no available dockets for the selected court session."
}
});
I have a date selector where it sets the variable's (courtDateSelected) value to the value selected and then sets off this script:
function reloadCheckinPageTables(){
console.log('begin');
console.log(courtDateSelcted);
console.log('end');
docketCheckedInDataTable.ajax.reload();
docketDataTable.ajax.reload();
docketPendingCheckoutDataTable.ajax.reload();
}
The problem is that my console log's the following:
begin
894
end
Which leads me to believe that the variable has been successfully updated, however, this variable's update value is not passed onto the data parameters in the DataTable.
For dynamically calculated data, you should use ajax.data as a function. Something like:
ajax: {
...
data: fundtion(d) {
d.court_date_id = courtDateSelected;
d.checked_in = 'true';
}
...
I have a datatable and a dropdown. I want to change the datatable after dropdown value change. First of all, I tried the simplest trial & error by getting return value from controller after dropdown changes value and it works smoothly. Here is my code:
$('#ID_Univ').change(function () {
$.ajax({
type: 'GET',
url: '#Url.Action("Get_Approved")',
data: { ID: _Id },
success: function (data) {
// data, I got return value
// do something here
}
});
});
and then here is my datatable code
var tbl_Approved = $('#tbl_Approved').DataTable({
lengthMenu: [10, 25, 50, 75, 100],
searchPane: {
columns: [':contains("Name")', ':contains("Period")'],
threshold: 0
},
////////////////////////////////////
processing: true,
serverSide: true,
ajax: { ??? },
////////////////////////////////////
columns: [
{ data: 'ID_Approved_Monthly', title: "ID" },
{ data: 'Name', title: "Name" },
{ data: 'Period', title: "Period" },
{ data: 'Approved', title: "Approved" },
{ data: 'Approved_Date', title: "Approval Date" },
{ data: 'Paid_Status', title: "Paid Date" },
],
columnDefs: [{
targets: [0],
visible: false,
searchable: false
}],
dom: 'Rlfrtip'
});
I put datatable code outside $(document).ready(function (). So, when the page reload, it just reload the datatable as variable and whenever dropdown's value changed it just call datatableName.ajax.reload();. That's the idea.
Now, my question are,
how do I put the ajax call in the datatable to reload datatable that det return value from controller (ASP .Net Core). I see someone did this flawlessly in youtube but it made by PHP. I have same idea with this youtube.
why I don't see any change in my datatable when dropdown value change ? even, I've put ajax.data according to "Add data to the request (returning an object)"
in this case, do I have to use server side ?
So here is my complete code, what I've been trying till right now and still get stuck.
<script type="text/javascript">
var tbl_Approved = $('#tbl_Approved').DataTable({
lengthMenu: [10, 25, 50, 75, 100],
searchPane: {
columns: [':contains("Name")', ':contains("Period")'],
threshold: 0
},
////////////////////////////////////
processing: true,
serverSide: true,
ajax: { //I get get stuck here :((
"datatype": "json",
type: 'GET',
url: '#Url.Action("Get_Approved")',
data: function (d) {
return $.extend({}, d, {
ID: $('#ID').val(),
})
}
},
////////////////////////////////////
columns: [
{ data: 'ID_Approved_Monthly', title: "ID" },
{ data: 'Name', title: "Acc Name" },
{ data: 'Period', title: "Period" },
{ data: 'Approved', title: "Approved" },
{ data: 'Approved_Date', title: "Approval Date" },
{ data: 'Paid_Status', title: "Paid Date" },
],
columnDefs: [{
targets: [0],
visible: false,
searchable: false
}],
dom: 'Rlfrtip'
});
$(document).ready(function () {
tbl_Approved_Allowance.draw();
$('#ID').change(function () {
tbl_Approved_Allowance.ajax.reload();
}
});
})
</script>
to solve this problem, I put ajax into .change(function()). Here is my code:
$('#ID').change(function () {
$.ajax({
type: 'GET',
url: '#Url.Action("Get_Approved")',
data: { ID: ID},
success: function (data) {
$('#tbl_Approved').DataTable({
destroy: true,
data: data,
lengthMenu: [10, 25, 50, 75, 100],
searchPane: {
columns: [':contains("Name")', ':contains("Period")'],
threshold: 0
},
columns: [[
{ data: 'ID_Approved_Monthly', title: "ID" },
{ data: 'Name', title: "Acc Name" },
{ data: 'Period', title: "Period" },
{ data: 'Approved', title: "Approved" },
{ data: 'Approved_Date', title: "Approval Date" },
{ data: 'Paid_Status', title: "Paid Date" },
],
dom: 'Rlfrtip'
});
}
})
});
This is event calling filtering while typing:
$("#txtPickItem").change(function (e) { doSearchPick(); });
This is my jqGrid:
$("#gridChooseItems").GridUnload();
jQuery("#gridChooseItems").jqGrid({
url: 'MyURL', datatype: "JSON",
colNames: ['id', 'Group', 'Source order'...],
colModel: [
{ name: 'del', index: ' ', width: 28, hidden: true },
{ name: 'id', index: 'id', hidden: true },
{ name: 'Group', index: 'Group', hidden: true },
{ name: 'Code', index: 'Code', width: 180 }...
],
loadComplete: function () { if ($("#txtPickItem").val()) { setTimeout('doSearchPick();', 100); } },
rowNum: 25, rowList: [10, 25, 50, 100, 200],
pager: '#pagerChooseItems',
sortname: 'id',
ondblClickRow: function (id) { AddItem(id); },
height: 580,
width: 1050,
ignoreCase: true,
loadonce: true,
viewrecords: true,
sortorder: "desc",
caption: "Available items"
});
My filtering function:
function doSearchPick() {
var grid = $("#gridChooseItems");
var filter = {
"groupOp": "AND", "rules":
[
{ "field": "Supplier", "op": "cn", "data": $("#txtPickItem").val() }
]
};
grid.jqGrid('setGridParam', { search: true, postData: { filters: filter } });
grid.trigger("reloadGrid", [{ page: 1 }]);
}
I have to reload grid after doubleclick and apply filter so previously double clicked item is not in grid anymore (many things happens in between).
When $("#txtPickItem") is empty, ondblClickRow and everything works fine, filtering works fine too.
Problem is that when some text is contained in txtPickItem, ondblClickRow doesn't fire and I don't understand why. I need this ondblClickRow event desperately.
EDIT:
AddItem function works fine as everything else if $("#txtPickItem") is empty
function AddItem(id) {
pData = {}
pData["ItemID"] = id;
jQuery.ajax({
url: 'URL',
type: "POST",
dataType: "JSON",
data: pData,
success: function (data) {
if (data == "msg1") {
PopulatePickGridItems(); //fill some other grid
}
else if (data == "msg2") {
$("#divMsg").html("<ul><li>err1. msg.</li></ul>")
$('#dlgMsg').dialog('open');
}
else {
$("#divMsg").html("<ul><li>err2. msg.</li></ul>")
$('#dlgMsg').dialog('open');
}
}
});
}
I make a grid with remote data
$("#orderGrid").kendoGrid({
scrollable: false,
columns: [
{ field: "order_id", title: "ID", width:"30px",template:"<a href='<%=request.getContextPath()%>/order/edit/#=order_id#'>#=order_id#</a>" },
{ field: "order_date", title: "Дата",width:"65px"},
{ field: "order_customer", title: "Заказчик"},
{ field: "order_transport", title: "Перевозчик"}
],
dataSource: {
transport: {
read: {
url: "<c:url value="/order/json"/>",
dataType: "json",
data: someData
},
},
type: "odata",
schema: {
data: function (data) {
return data["data"];
},
total: function (data) {
return data["count"];
}
},
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
pageable: true,
sortable: true,
filterable: true,
});
And after I wanna make filter and update data
var grid = $("#orderGrid").data("kendoGrid");
grid.dataSource.read(filterData);
But after! when i paging grid it send old data (someData) to server and error occured....and i need filterData....
grid.refresh();
Do not help......
Answer
transport: {
read: {
url: "<c:url value="/order/json"/>",
dataType: "json",
data: function(){
return filterData;
}
},
},
I created a grid and one of my column has a custom button in each row. When I click the button my click event is not invoked.
My jqgrid:
$('#QuoteLineTable').jqGrid({
url: $('#url').val(),
datatype: 'json',
type: 'POST',
postData: { Id: $("#Id").val() },
colNames: ['Id', 'Quote Number', 'Valid Until Date','View Line Item'],
colModel: [
{ name: "QuoteLineId", index: "QuoteLineId", hidden: false, hidedlg: true },
{ name: 'QuoteNumber', index: "QuoteNumber" },
{ name: 'ValidUntil', formatter: "date", formatoptions: { newformat: "d/m/Y" }, width: '100px' },
{ name: 'View Line Item', formatter: viewLineBtn }
],
multiselect: true,
emptyrecords: "No Quote Line to view",
gridview: true,
autoencode: true,
loadtext: "Loading...",
loadonce: true,
rowNum: 3,
rowList: [10, 20, 30],
pager: '#LinePager',
height: '100%',
caption: "Quote List",
autowidth: true,
sortname: 'QuoteNumber',
ajaxGridOptions: { type: 'POST', contentType: "application/json; charset=utf-8" },
jsonReader: {
repeatitems: false,
root: "rows",
page: "page",
total: "totalPages",
records: "totalRecords",
id: "QuoteLineId"
},
serializeGridData: function(postData) {
return JSON.stringify(postData);
},
onCellSelect: function(rowid,e) {
alert("rowid=" + rowid );
},
ondblClickRow: function(rowid) {
var $model = $('#LineItemMyModal');
$.ajax({
type: "GET",
url: $('#urlItemDetails').val(),
data: { LineId: rowid },
success: function(r) {
$model.html(r);
$model.modal('show');
}
});
}
}).navGrid('#QuoteLinePager', { edit: false, add: false, del: false, search: true });
function viewLineBtn(cellvalue, options, rowObject) {
return "<button class=\"viewLineItem\">View Line Item</button>"
};
$('.viewLineItem').click(function (rowId) {
alert("hi");
alert(rowId);
});
Basically I am not sure how to call the click event for button class= viewLineItem.
I tried to use onCellSelect or beforeSelectRow event but I also need to use ondblClickRow to populate a modal. So I am looking for other options without using oncellSelect.
Try something like this.
$('#QuoteLineTable').jqGrid({
url: $('#url').val(),
datatype: 'json',
type: 'POST',
postData: { Id: $("#Id").val() },
colNames: ['Id', 'Quote Number', 'Valid Until Date','View Line Item'],
colModel: [
{ name: "QuoteLineId", index: "QuoteLineId", hidden: false, hidedlg: true },
{ name: 'QuoteNumber', index: "QuoteNumber" },
{ name: 'ValidUntil', formatter: "date", formatoptions: { newformat: "d/m/Y" }, width: '100px' },
{ name: 'View Line Item', formatter: viewLineBtn }
],
multiselect: true,
emptyrecords: "No Quote Line to view",
gridview: true,
autoencode: true,
loadtext: "Loading...",
loadonce: true,
rowNum: 3,
rowList: [10, 20, 30],
pager: '#LinePager',
height: '100%',
caption: "Quote List",
autowidth: true,
sortname: 'QuoteNumber',
ajaxGridOptions: { type: 'POST', contentType: "application/json; charset=utf-8" },
jsonReader: {
repeatitems: false,
root: "rows",
page: "page",
total: "totalPages",
records: "totalRecords",
id: "QuoteLineId"
},
serializeGridData: function(postData) {
return JSON.stringify(postData);
},
onCellSelect: function(rowid,e) {
alert("rowid=" + rowid );
},
ondblClickRow: function(rowid) {
var $model = $('#LineItemMyModal');
$.ajax({
type: "GET",
url: $('#urlItemDetails').val(),
data: { LineId: rowid },
success: function(r) {
$model.html(r);
$model.modal('show');
}
});
}
}).navGrid('#QuoteLinePager', { edit: false, add: false, del: false, search: true });
function viewLineBtn(cellvalue, options, rowObject) {
var rowid= options.rowid;
var button = "<button class=\"viewLineItem\" id="+ rowid+">View Line Item</button>"
$('#' + rowid).die();
$('#' + rowid).live('click', function (rowId) {
alert("hi");
alert(rowId);
});
};
It works for me:
$('#QuoteLineTable').jqGrid({
....
colModel: [
...
{ name: 'View Line Item', formatter: viewLineBtn }
]
loadComplete: function (data) {
console.log(data); // You can view the object
let rowDataArray = data.rows;
for (let i = 0, j = rowDataArray.length; i < j; i++)
{
let temp = rowDataArray[i];
$("#btn_" + temp.id).click(() => {
m_alert(temp.content);
});
}
}
});
function viewLineBtn(cellvalue, options, rowObject)
{
return "<button id='btn_" + rowObject.id + "'>View Line Item</button>"
}