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'
});
}
})
});
Related
I'm using the below code to generate the table, but I need to show code as link where I should able to run custom code to navigate to another record
$('#customerdt').DataTable({
"bInfo": false,
data: accountData,
columns: [
{ data: 'code' },
{ data: 'customerid' },
{ data: 'name' },
{ data: 'telephone' },
{ data: 'emailaddress' },
{ data: 'joiningdate' }
],
"bDestroy": true
});
Use the columns.render option
const table = $('#customerdt').DataTable({
"bInfo": false,
data: accountData,
columns: [
{
data: 'code',
render: (data, type, row) => `${data}`
}
{ data: 'customerid' },
{ data: 'name' },
{ data: 'telephone' },
{ data: 'emailaddress' },
{ data: 'joiningdate' }
],
"bDestroy": true
});
table.on('click', '.my-class', function() {
const emailAddress = this.getAttribute('data-email');
}
This is my datatable code:
table = $('#datatable-buttons').DataTable({
lengthChange: false,
pageLength: 25,
order: [ 0, 'desc' ],
//buttons: ['copy', 'excel', 'pdf', 'colvis']
columns: [
{ data: "sample_lab_ref" },
{ data: "sample_client_ref" },
{ data: "sample_client_ref2" },
{ data: "sample_client_ref3" },
{ data: "sample_date" },
{ data: "report_date" },
{ data: "test_parameter_name" },
{ data: "test_parameter_sop" },
{ data: "test_technique_name" },
{ data: "test_value_text" },
{ data: "test_units" }
],
columnDefs: [
{
targets: [4, 5],
visible: false,
searchable: false
}
],
ajax: {
url: "/assets/ajax/test_data_ajax_handler.php",
type: "POST",
data: {
action: "getTestData",
user_data: '<?=json_encode($userData)?>'
}
},
buttons: {
buttons: [
{ extend: 'copy', className: 'btn-info' },
{ extend: 'pdf', className: 'btn-danger' },
{
extend: 'csv',
className: 'btn-success',
text: 'Export to CSV',
exportOptions: {
modifier: {
search: 'applied'
}
}
},
{ extend: 'colvis', className: 'btn-primary' },
]
},
initComplete: function(settings, json) {
table.buttons().container()
.appendTo('#datatable-buttons_wrapper .col-md-6:eq(0)');
}
});
Works fine, but in the event the function in the ajax handler returns NULL (no rows found). How can I tell the datatable to display something like "No data found". Right now it gives me an invalid json syntax error.
You can create empty json like this:
{
"data": [],
"total": 0,
"recordsTotal": 0,
"recordsFiltered": 0
}
Try using dataSrc and pass a function to process your data.. Hope the attached data pre-processing callback will be called even on HTTP errors
sample code
$('#example').dataTable( {
"ajax": {
"url": "data.json",
"dataSrc": function ( json ) {
for ( var i=0, ien=json.data.length ; i<ien ; i++ ) {
json.data[i][0] = '<a href="/message/'+json.data[i][0]+'>View message</a>';
}
return json.data;
}
}
} );
From here Display warning if records null Datatables AJAX - dataSrc
You can fix it with dataSrc
ajax: {
url: "/assets/ajax/test_data_ajax_handler.php",
type: "POST",
data: {
action: "getTestData",
user_data: '<?=json_encode($userData)?>'
},
dataSrc: function(data){
if(data.data == null){
return [];
} else {
return data.data;
}
}
},
This is a jQuery code of my sample project to get details from application side to display in front in a grid which is build by jsGrid.
$("#part_table").jsGrid({
height: "auto",
width: "100%",
autoload: true,
editing: true,
sorting: true,
paging: true,
pageSize: 10,
inserting: true,
loadIndication: false,
filtering: true,
headerRowClass: 'table-green-header',
controller: {
loadData: function (filter) {
function.....
},
updateItem: function (item) {
function.....
}
},
fields: [
{ name: "Id", type: "number", visible: false },
{
name: "CatalogueId", type: "select", **items**: catalouges, valueField: "Id", textField: "CatalougeName", selectedIndex : -1 , title: "Catalouge Name", align: "center"
},
{ name: "DistributorPrice", type: "number", title: "Distributor Price", align: "center", filtering: false, sorting: false },
{ name: "IsActive", type: "checkbox", filtering: false, sorting: false },
{ type: "control" }
],
rowClick: function (args) {
return false;
},
});
Can anyone say how to get a list of items to field by calling to application side via AJAX call ?
Thanks
Load items in advance and then use result in the grid field config, e.g.:
$.ajax({
type: "GET",
url: "/countries/"
}).done(function(countries) {
countries.unshift({ id: "0", name: "" });
$("#jsGrid").jsGrid({
...,
fields: [
...
{ name: "country_id", title: "Country", type: "select", width: 100, items: countries, valueField: "id", textField: "name" }
]
});
});
You can find an example in the jsgrid sample project
You can do multiple simultaneous requests before the grid launches
$.when(
$.get("/api/v1/clients", function(clients) {
db.clients = clients;
}),
$.get("/api/v1/owners", function(owners) {
db.owners = owners;
})
).then(function() {
$("#jsGrid").jsGrid({
...,
fields: [
{ name: "client", title: "Client", type: "select", items: db.clients, valueField: "name", textField: "name" },
{ name: "owner", title: "Owner", type: "select", items: db.owners, valueField: "short_name", textField: "short_name" },
]
});
});
you write the ajax call in loadData of the controller.. something like:
controller: {
loadData: function(filter) {
return $.ajax({
type: "GET",
url: "/api/data",
data: filter,
dataType: "json"
});
}
}
further reference https://github.com/tabalinas/jsgrid-webapi
I am new to web development, I have run into this problem and have researched and tried many other methods to no avail. I need to populate a drop down list in a jqgrid only with values that are in my database. The url that I am using to do this gives me the correct response in JSON as follows (note that I only sent through selected fields):
{
"serviceBranchResult": [
{
"branch_services": [],
"queues": [],
"service_description": null,
"service_id": 2,
"service_name": "Forex",
"service_status": null
},
{
"branch_services": [],
"queues": [],
"service_description": null,
"service_id": 3,
"service_name": "Tellers",
"service_status": null
}
]
}
When I try to do a dropdownlist from the method below without reading the json from the url it works 100% however it isnt dynamic, I use the method getAllSelectOptions() and where I am using it in the grid looks like this:
function getAllSelectOptions() {
var services = {
'1':'Forex', '2':'Tellers', '3':'Consultants'};
return services;
}
My code for the grid:
url: "http://localhost:8080/service.svc/employees/3"
datatype: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
height: '250',
colNames: ['ID', 'Name', 'Surname', 'Username', 'Email', 'Branch ID', 'User Type', 'Status', 'Speciality'],
colModel: [
{ name: 'employee_id', index: 'employee_id'},
{ name: 'employee_name', index: 'employee_name', editable: true },
{ name: 'employee_surname', index: 'employee_surname', editable: true },
{ name: 'employee_username', index: 'employee_username', editable: true },
{ name: 'employee_email', index: 'employee_email', editable: true },
{ name: 'branch_id', index: 'branch_id', editable: true },
{ name: 'user_type', index: 'user_type', editable: true },
{ name: 'employee_state', index: 'employee_state', editable: true },
{ name: 'employee_speciality', index: 'employee_speciality', editable: true,
sortable: true,
align: 'center',
editable: true,
cellEdit: true,
edittype: 'select',
formatter: 'select',
editoptions: { value: getAllSelectOptions() }
}],
rowNum: 20,
rowList: [10, 20, 30],
pager: '#pager_jqgrid',
And this works perfectly.
However I use this following method to potentially replace the getAllSelectOptions() method and it does return the information when I use alert boxes, but does not work.
function availAtBranch() {
$.ajax({
type: "GET",
url: "http://localhost:8080/service.svc/branch/3",
dataType: "json",
success: function (data) {
$.each(data.serviceBranchResult, function (i, obj) {
//alert(obj.service_id + ":" + obj.service_name);
var div_data = obj.service_name + ":" + obj.service_name;
//alert(div_data);
});
return div_data;
}
});
I think it has something to do with how in parsing the JSON to the editoptions method, or sending an object through. How do I get my JSON to be in the format as described in the getAllSelectOptions() method, or how do I display my data in the dropdownlist. Thank you in advance
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');
}
}
});
}