Everything work fine on code below to fetch user logs:
js:
<script>
$(document).ready(function () {
var table =$('#systemLogs').DataTable({
responsive: true,
processing: true,
serverSide: true,
"language": {
"url": "/datatables/media/plug-in/Persian.json"
},
ajax: '{!! url('/admin/systemLogs/data/systemLogsDataTable') !!}',
columns: [
{ data: 'name', name: 'name' },
{ data: 'message_text', name: 'message_text' },
{ data: 'remote_addr', name: 'remote_addr' },
{ data: 'log_created_at', name: 'management_logs.created_at' },
{ data: 'log_updated_at', name: 'management_logs.updated_at' },
]
});
});
</script>
routes:
Route::get('/systemLogs/data/systemLogsDataTable','SystemLogsController#systemLogsDataTable');
public function systemLogsDataTable()
{
$logs= ManagementLog::select('management_logs.message_text','management_logs.remote_addr','management_logs.created_at as log_created_at','management_logs.updated_at as log_updated_at','managements.name')->leftJoin('managements','management_logs.management_id','=','managements.id');
return Datatables::of($logs)->make(true);
}
It works fine for me but when I want to fetch just 2 fields from database it will give me
DataTables warning:table id=systemLogs - invalid JSON response.
but some times it will work ok.
<script>
$(document).ready(function () {
var table =$('#systemLogs').DataTable({
responsive: true,
processing: true,
serverSide: true,
"language": {
"url": "/datatables/media/plug-in/Persian.json"
},
ajax: '{!! url('/admin/systemLogs/data/systemLogsDataTable') !!}',
columns: [
{ data: 'name', name: 'name' },
{ data: 'message_text', name: 'message_text' },
]
});
});
</script>
I have understood which the problem is from middleware:
public function handle($request, Closure $next,$guard = 'admin')
{
if(!Auth::guard($guard)->check()){
return redirect('/administrator/logout');
}else{
return $next($request);
}
}
when I changed it to:
public function handle($request, Closure $next,$guard = 'admin')
{
return $next($request);
}
It works fine so it means the problem is from AJAX.
what do I have to do?
It's because if you're not logged into application the response is gonna be a redirect and this is a invalid AJAX response, you can try this to handle redirect response:
$(document).ready(function () {
var table =$('#systemLogs').DataTable({
responsive: true,
processing: true,
serverSide: true,
"language": {
"url": "/datatables/media/plug-in/Persian.json"
},
ajax: function(data, callback, settings) {
// make a regular ajax request
$.get('{!! url('/admin/systemLogs/data/systemLogsDataTable') !!}', function(res) {
if(res.redirect)
window.location.href = res.redirect;
callback({
data: JSON.parse(res)
});
});
},
columns: [
{ data: 'name', name: 'name' },
{ data: 'message_text', name: 'message_text' },
{ data: 'remote_addr', name: 'remote_addr' },
{ data: 'log_created_at', name: 'management_logs.created_at' },
{ data: 'log_updated_at', name: 'management_logs.updated_at' },
]
});
});
First, are you using php artisan serve? I think yes, so I suggest you use homestead/valet or any apache/nginx stack.
It's been a known weird bug of the package where Laravel randomly returns redirect/404 response when using artisan serve.
-- Edit --
Updated the package documentation and advise the known bug.
https://github.com/yajra/laravel-datatables#php-artisan-serve-bug
Related
Datatable is not displaying the response of an AJAX call to flask backend.
The data is retrieved as I can see it in the console.log of the success field of the AJAX call, however its not populating in the table.
Here is the JSON:
{'events':
[
{
'TIME': 'Evening',
'DESCRIPTION': 'test1'
},
{
'TIME': 'Morning',
'DESCRIPTION': 'test2'
}
]
}
This is the JS part:
function load_table() {
var payload = {'from_date': $('#from_date').val(), 'to_date': $('#to_date').val()}
$('#table').DataTable({
pageLength: 50,
paging: true,
ajax: {
url: "data/get-events/" + JSON.stringify(payload),
dataType: "json",
type: 'GET',
error: function(e){
alert(e);
},
success: function(e){
console.log(e);
},
dataSrc: 'events'
},
columns: [
{ title: 'Time', data: 'TIME'},
{ title: 'Event', data: 'DESCRIPTION'}
],
bDestroy: true,
});
}
I tried the tens of answers to my similar question but none of them worked.
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');
}
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'
});
}
})
});
I have Odata WebApi, and I want to populate my dropdownlist with data from there.
I have datasource:
var postsDataSource = new kendo.data.DataSource({
type: 'odata',
serverFiltering: true,
transport: {
read: {
url: "/odata/Posts",
dataType: "json"
},
},
schema: {
model: kendo.data.Model.define({
Id: "Id",
RegionId: "RegionId"
}),
data: function (res) {
debugger;//this code is inaccessible!
console.log(res);
return res.value;
}
},
});
and dropdownlist like this:
var posts = $("#searchPost").kendoDropDownList({
optionLabel: "Выберите регион...",
dataTextField: "NameRu",
dataValueField: "Id",
dataSource: postsDataSource,
}).data("kendoDropDownList");
This part of code executes odata query and return me the following json response in the firebug's console:
{
"odata.metadata":"http://localhost:11029/odata/$metadata#Posts","odata.count":"13","value":[
{
"Id":0,"Number":"Lenina45","RegionId":1,"NameRu":"\u041b\u0435\u043d\u0438\u043d\u0430 45","NameKz":"\u041b\u0435\u043d\u0438\u043d\u0430 45","ShortName":"\u041b\u0435\u043d\u0438\u043d\u0430 45","DateBegin":null,"DateEnd":null,"OptimisticLockField":null
},{
"Id":1,"Number":"Zhumabaeva15","RegionId":2,"NameRu":"\u0416\u0443\u043c\u0430\u0431\u0430\u0435\u0432\u0430 15","NameKz":"\u0416\u0443\u043c\u0430\u0431\u0430\u0435\u0432\u0430 15","ShortName":"\u0416\u0443\u043c\u0430\u0431\u0430\u0435\u0432\u0430 15","DateBegin":null,"DateEnd":null,"OptimisticLockField":null
},
.....
]
}
Right after this response I am getting the following strange error:
TypeError: d.d is undefined;
And dropdownlist doesn't show me above json response.
When I populated kendo grid with odata web api, the following code in datasource solved my problem:
schema: {
data: function (res) {
return res.value;
}
},
but now, when I use it for dropdownlist it doesn't work at all, it's inaccessible.
PS> Sorry for my bad English.
You Data Is on the inner object "value" on your response , your response consist on page size , metadata url so we need to prase the data that kendo dataSource can understand here is a exsample
: Note Remove "type: 'odata'" and check , since you are saying the dataSource where the Data is from the Data function no need of it as I think.
var postsDataSource = new kendo.data.DataSource({
serverFiltering: true,
transport: {
read: {
url: "/odata/Posts",
dataType: "json"
},
},
schema: {
model: {
Id: "Id",
fields: {
Id: { type: "number" },
NameRu: { type: "string" },
NameKz: { type: "string"},
ShortName: { type: "string" }
}
},
data: function (response) {
return response.value;
},
total: function(response) {
return response.odata.count;
}
},
});
try this hope this helps.
I am developing a web application which deals with interactive grids. I am using Kendo UI for displaying grids and doing CRUD operations. I am new to Kendo UI. We are performing database calls using jquery, Ajax only. I was able to make it read the data from the database and display it. But I am stuck at CRUD operations. How to get the event that a specific row or a specific single data is changed and perform the update. Please help me to understand how to do the crud operations. I couldn't find it in detail anywhere. There are 8 parameters which are in the first column. The user should be able to change the rest of the data except the parameters.
following is the code for Grid. CreateWBDGridData triggers the database service call and creates the table. gridSource is JSON data getting from the database after converting through Json convert function.
$(document).ready(function()
{
var param ="HOLE_DIAMETER|4.875_CASING_ID|5.5_GRAVEL_PACK|NET_PERF_THICKNESS|PERF_DIAMETER|PERF_GRAVEL_PERM_#19k|GRAVEL_BETA_FACTOR_#19K|SHOT_DENSITY";
$.when(GetWBDGridDataByWell(param)).then(function (data) {
});
});
function CreateWBDGridData(gridSource) {
if (gridSource == undefined) return;
console.log(gridSource);
$("#grid").kendoGrid({
dataSource: {
data: gridSource,
schema: {
model: {
fields: {
ParameterName: { type: "string" },
Zone_1: { type: "number" },
Zone_2: { type: "number" },
Zone_3: { type: "number" },
}
}
},
// pageSize: 20
},
//height: 550,
//scrollable: true,
//sortable: true,
//filterable: true,
//reorderable: true,
resizable:true,
//pageable: {
// input: true,
//numeric: false
//},
columns: [
{ field: "ParameterName", title: "Lucius 01", width: 300 },
{ field: "Zone_1", title: "Zone 1", width: 100 },
{ field: "Zone_2", title: "Zone 2", width: 100 },
{ field: "Zone_3", title: "Zone 3", width: 100 },
]
});
}
Controller
var dspstore = "System.Sources.Db.MsSql.DSPStore";
function GetWBDGridData(queryName, param) {
var varData = CreateParamQuery(dspstore, queryName, param);
CallService(GetWBDGridDataCompleted, varData);
}
var GetWBDGridDataCompleted = function (result) {
if (varDataType == "json") {
var myItems = $.parseJSON(result.GetDataItemsResult);
CreateWBDGridData(myItems);
}
}
Service call
function CallService(ServiceCompleted, varData) {
$.support.cors = true;
$.ajax({
context: this,
disableCaching: false,
headers: {
"Access-Control-Allow-Origin": '*',
'Accept': 'application/json',
'Content-Type': 'application/json'
},
type: varType, //GET or POST or PUT or DELETE verb
url: varUrl, // Location of the service
data: varData, //Data sent to server
//contentType: varContentType, // content type sent to server
dataType: varDataType, //Expected data format from server
processdata: varProcessData, //True or False
success: function (msg) {//On Successfull service call
ServiceCompleted(msg);
},
error: ServiceFailed// When Service call fails
});
}
Ok, as I Understand there 8 parameters which are the first column, have had has 3 more items which user can edit if so do as below.
$("#grid").kendoGrid({
dataSource: {
transport: {
read: function (options) {
$.ajax({
url: "/Your Controller/your read Action",
dataType: "json",
cache: false,
success: function (result) {
options.success(result);
},
error: function (result) {
options.error(result);
}
});
},
update: function (options) {
$.ajax({
url: "/Your Controller/your Update Action",
dataType: "json",
cache: false,
data:{model:options.data.models},
success: function (result) {
options.success(result);
},
error: function (result) {
options.error(result);
}
});
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
schema: {
model: {
fields: {
ParameterName: { type: "string",editable: false },
Zone_1: { type: "number",editable: true, validation: { required: true } },
Zone_2: { type: "number",editable: true, validation: { required: true } },
Zone_3: { type: "number" ,editable: true, validation: { required: true }},
}
}
},
pageSize: 10
},
resizable:true,
columns: [
{ field: "ParameterName", title: "Lucius 01", width: 300 },
{ field: "Zone_1", title: "Zone 1", width: 100 },
{ field: "Zone_2", title: "Zone 2", width: 100 },
{ field: "Zone_3", title: "Zone 3", width: 100 },
]
});
}
Use the model to specify the editable and non-editable fields and Your Data Source Data parameter does not use unless you're doing local calls, to do server calls call it as a function as shown above.
and your Controller action should look like below : (I Assume your using MVC)
[HttpGet]
public ActionResult ReadGridJson()
{
return Json(yourlist, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult UpdateGridJson(YourModelType model)
{
//update the DB and return the updated item
return Json(updateItem, JsonRequestBehavior.AllowGet);
}
Hope this helps, For more info check out the API DOC http://docs.telerik.com/kendo-ui/api/web/grid