Can't Display Datetime on datatable Plugins - javascript

I am displaying a list from the database, but the date time column is showing this error:
/Date(1492421931187)/
JS:
<script>
$(document).ready(function () {
$('#myTable').DataTable({
"ajax": {
"url": "Default/load",
"type": "GET",
"datatype" : "json"
},
"columns": [
{ "data": "Id", "autowidth": true },
{ "data": "Name", "autowidth": true },
{ "data": "Phone", "autowidth": true },
{ "data": "Num", "autowidth": true },
{ "data": "Date", "autowidth": true },
{ "data": "Message", "autowidth": true }
]
});
});
</script>
Controller:
var data = db.data_customer.Select(x => new { x.Id, x.Name, x.Message, x.Num,
x.Phone, x.Date }).OrderBy(x => x.Date).ToList();
return Json(new { data = data }, JsonRequestBehavior.AllowGet);
Json:
data
:
[{Id: 8, Name: "12312", Message: "123123", Num: 12, Phone: "3123132", Date: "/Date(1492421931187)/"}]

You need to change date format. Refer below code. In this code I am passing your JSON date value in date variable and as per requirement I am displaying date
$(document).ready(function(){
var dt=new Date(1492421931187);//Your JSON date
var getDate=dt.getDate();
var getMonth=dt.getMonth()+1;
var getYear=dt.getFullYear();
$("#abc").html("Date (dd/mm/yyyy)="+getDate+" / "+getMonth+" / "+getYear);
$("#abcd").html("Date full date ="+dt);
});
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.0.min.js">
</script>
<p id="abcd">Full Date</p>
<p id="abc">dd/mm/yyyy</p>
I have created a function which changes date format so that your issue will be resolved. I have updated my code in jsfiddle. Hopefully it will help you http://jsfiddle.net/GSB/b8bdjhhq/5/

Related

DataTable change properties with Media Query

I want to change the scrollX property of my DataTable to true when switched to mobile but I don't know how to do that, I have tried using media query but it does not seem to work. Any idea?
var mobview = window.matchMedia( "(max-width: 425px)" );
$(document).ready(function() {
var table = $('#datatable').DataTable( {
"scrollX": false,
"bLengthChange": false,
"ajax": "src/json/AttendanceReport.json",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "id" },
{ "data": "FullName" },
{ "data": "DaysPresent" },
{ "data": "DaysAbsent" },
{"data":"DaysLate"}
],
"order": [[1, 'asc']]
} );
if (mobview.matches) {
table.scrollX=true;
}
$(document).ready(function() {
var mobview = window.matchMedia( "(max-width: 425px)" );
var table = $('#datatable').DataTable( {
"scrollX": !mobview.matches,
"bLengthChange": false,
"ajax": "src/json/AttendanceReport.json",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "id" },
{ "data": "FullName" },
{ "data": "DaysPresent" },
{ "data": "DaysAbsent" },
{"data":"DaysLate"}
],
"order": [[1, 'asc']]
});
EDIT
matchMedia() method returns a object that can then be used to determine if the document matches the media query string.
mediaQueryList = window.matchMedia(mediaQueryString)
Where mediaQueryString stores information on a media query.
You can invoke multiple mediaQueryString as well, Let say an example
const mediaQueryList = window.matchMedia('(min-width: Xpx), (max-height: Ypx)');
It will result in output as follows
MediaQueryList {media: "not all, not all", matches: false, onchange: null}
Description of output (MediaQueryList)
media - A DOMString representing a serialized media query.
matches - Bolean (true/False)

How to show jQuery Datatable error in a bootstrap alert-warning div rather than the alert box

I am working on an ASP.NET Core 2.1 website and I am using Datatables.net to display my record lists retrieved from a backend API.
This issue I am trying to resolve is that, whenever an error occurs while retrieving the data from the backend API, I want the error message to appear in a Bootstrap alert-error DIV on the same page as the datatable.
I have looked at https://datatables.net/forums/discussion/30033/override-default-ajax-error-behavior and Enable datatable warning alert but I am not strong in javascript so I am having some difficulty determining how to implement this feature.
Currently, I have the datatable set up in my cshtml page as follows;
<script>
jQuery(document).ready(function ($) {
var table = $("#sitelist").DataTable({
"processing": true,
"serverSide": true,
"filter": true,
"orderMulti": false,
"ajax": {
"url": "/Sites/LoadData",
"type": "POST",
"datatype": "json"
},
"columnDefs": [
{ "orderable": false, "targets": 6 },
{ "className": "text-center", "targets": [4, 5] },
{
"targets": [4, 5],
"createdCell": function(td, cellData, rowData, row, col) {
if (cellData) {
$(td).html('<i class="far fa-check-circle text-primary""></i>');
} else {
$(td).html('<i class="far fa-times-circle text-danger""></i>');
}
}
}
],
"columns": [
{ "data": "Id", "name": "Id", "autoWidth": true, "defaultContent": "" },
{ "data": "SiteName", "name": "SiteName", "autoWidth": true, "defaultContent": "" },
{ "data": "CompanyId", "name": "CompanyId", "autoWidth": true, "defaultContent": "" },
{ "data": "CompanyName", "name": "CompanyName", "autoWidth": true, "defaultContent": "" },
{ "data": "IsAdminSite", "name": "IsAdminSite", "autoWidth": true, "defaultContent": "" },
{ "data": "IsEnabled", "name": "IsEnabled", "autoWidth": true, "defaultContent": "" },
{
"render": function (data, type, full, meta) { return `<i class="far fa-edit text-primary" title="Edit">`; }
}
],
// From StackOverflow http://stackoverflow.com/a/33377633/1988326 - hides pagination if only 1 page
"preDrawCallback": function (settings) {
var api = new $.fn.dataTable.Api(settings);
var pagination = $(this)
.closest('.dataTables_wrapper')
.find('.dataTables_paginate');
pagination.toggle(api.page.info().pages > 1);
}
});
});
</script>
And here is the loaddata action in my SitesController class;
public async Task<IActionResult> LoadData()
{
try
{
await SetCurrentUser();
ViewData["Role"] = _currentRole;
var draw = HttpContext.Request.Form["draw"].FirstOrDefault();
var start = Request.Form["start"].FirstOrDefault();
var length = Request.Form["length"].FirstOrDefault();
var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();
var sortColumnDirection = Request.Form["order[0][dir]"].FirstOrDefault();
var searchValue = Request.Form["search[value]"].FirstOrDefault();
var pageSize = length != null ? Convert.ToInt32(length) : 0;
var skip = start != null ? Convert.ToInt32(start) : 0;
var request = new SitesGetListRequest
{
OrderBy = SetOrderBy(sortColumn, sortColumnDirection),
Filter = SetFilter(searchValue),
PageNumber = (skip / pageSize) + 1,
PageSize = pageSize
};
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
var endpoint = $"api/companies/{SetCompanyId()}/sites/filtered";
var siteData = await _client.GetSiteListAsync(request, endpoint, token);
if (siteData.Sites != null)
{
return Json(new
{
draw,
recordsFiltered = siteData.Paging.TotalCount,
recordsTotal = siteData.Paging.TotalCount,
data = siteData.Sites.ToList()
});
}
//TODO: Find a way to pass error to a Bootstrap alert-warning DIV rather than the jQuery (javascript) alert box
var errorMessage = $"Http Status Code: {siteData.StatusCode} - {siteData.ErrorMessages.FirstOrDefault()}";
return Json(new
{
data = "",
error = errorMessage
});
}
catch (Exception ex)
{
const string message = "An exception has occurred trying to get the list of Site records.";
_logger.LogError(ex, message);
throw;
}
}
As it stands right now, If an error exists in the object returned from the API call, I pass a message to the error property in the returned json and it shows up as an javascript alert popup box on my cshtml page and when I click OK, the datatable displays "No records found", as shown in the images below;
and...
What I want is for the error message to display in a bootstrap alert-danger div at the top of the cshtml page. I so not want the alert popup to appear and I still want the datatable to show "No records found".
I think that what I am looking for is described on Enable datatable warning alert...
Disable the alert popup by using
$.fn.dataTable.ext.errMode = 'none';
And pass the error message to the BootStrap div using
$('#example')
.on( 'error.dt', function ( e, settings, techNote, message ) {
console.log( 'An error has been reported by DataTables: ', message );
} )
.DataTable();
but instead of
console.log( 'An error has been reported by DataTables: ', message );
use something like
$("#error").html(MY ERROR MESSAGE HERE);
and assign id="error" to the bootstrap div.
But, I am having trouble figuring out how to trigger the Ajax call from my loaddata method in the SitesController and also how to correctly add the error event to the beginning of my datatable script.
Before I burn more time trying to work this out, I thought I would put this on SO and see if anyone with javascrit/jquery experience can provide some guidance.
You can add the error property to the ajax call. Probably the best will be to use fnServerData.
jQuery(document).ready(function ($) {
var table = $("#sitelist").DataTable({
"processing": true,
"serverSide": true,
"filter": true,
"orderMulti": false,
"sAjaxSource": "/Sites/LoadData",
"fnServerData": function (sSource, aoData, fnCallback) {
$.ajax({
"dataType": 'json',
"type": "GET",
"url": sSource,
"data": aoData,
"cache": false,
"success": function (data) {
fnCallback(data);
},
"error": function(error){
$("#error").html(error);
}
});
},
"columnDefs": [
{ "orderable": false, "targets": 6 },
{ "className": "text-center", "targets": [4, 5] },
{
"targets": [4, 5],
"createdCell": function(td, cellData, rowData, row, col) {
if (cellData) {
$(td).html('<i class="far fa-check-circle text-primary""></i>');
} else {
$(td).html('<i class="far fa-times-circle text-danger""></i>');
}
}
}
],
"columns": [
{ "data": "Id", "name": "Id", "autoWidth": true, "defaultContent": "" },
{ "data": "SiteName", "name": "SiteName", "autoWidth": true, "defaultContent": "" },
{ "data": "CompanyId", "name": "CompanyId", "autoWidth": true, "defaultContent": "" },
{ "data": "CompanyName", "name": "CompanyName", "autoWidth": true, "defaultContent": "" },
{ "data": "IsAdminSite", "name": "IsAdminSite", "autoWidth": true, "defaultContent": "" },
{ "data": "IsEnabled", "name": "IsEnabled", "autoWidth": true, "defaultContent": "" },
{
"render": function (data, type, full, meta) { return `<i class="far fa-edit text-primary" title="Edit">`; }
}
],
// From StackOverflow http://stackoverflow.com/a/33377633/1988326 - hides pagination if only 1 page
"preDrawCallback": function (settings) {
var api = new $.fn.dataTable.Api(settings);
var pagination = $(this)
.closest('.dataTables_wrapper')
.find('.dataTables_paginate');
pagination.toggle(api.page.info().pages > 1);
}
});
});
</script>

JQuery Datatables not load immediately/disable autolaod

I am using JQuery Datatables 1.10.15 I would like to search first before loading the data because i have 300,000+ rows, maybe something like
if (table not loaded) {
(load the table)
}
else {
(Search)
}
or any other ways, please help me
this is my code:
var mytable = $('#myDatatable').DataTable({
"ajax": {
"url": '/Home/GetAllRecords',
"type": "POST",
"datatype": "json",
"data": (records)
},
"columns": [
{ "data": "id", "autoWidth": true },
{ "data": "name", "autoWidth": true }
]
});
$('#btnSearch').on("click", function () {
mytable.ajax.reload();
});

jquery datatable binding data property to content that is displayed

I have my jQuery datatable plugin installed and I've initialized it like this:
$('#datatable-responsive2').DataTable({
// data: data,
// deferRender: true,
"pageLength": 25,
"bLengthChange": false,
"processing": true,
"serverSide": true,
"filter": false,
"orderMulti": false,
"ajax": {
"url": "/Administrator/LoadData/",
"type": "POST",
"datatype":"json"
},
"columns": [
{ "data": "FirstName", "name": "Lela", "autoWidth": true },
{ "data": "Email", "name": "Email", "autoWidth": true },
{ "data": "Active", "name": "Status", "autoWidth": true },
{ "targets": -1, "data": "UserId", "defaultContent": "<button>Click!</button>", "autoWidth": true },
{ "data": "FirstName", "name": "Full name", "autoWidth": true }
]
});
Please note this column:
{ "targets": -1, "data": "UserId", "defaultContent": "<button>Click!</button>", "autoWidth": true }
I've followed their documentation on how to render an HTML element there... But what I need now and wasn't able to figure how do I actually set a certain attribute for this HTML element inside the datatable when its being generated...
As u can see I've set data source for the datatable as UserId, and now I'd like each button "Click" to have value whatever the value of UserId is...
Can someone help me out?
P.S. so I want to output an HTML element in that column whos structure would be something like this:
<button values="whatever the value of userId is..?">Click me event</button>
You would need to define the render property of the column for that which would be the following :
{
"targets": -1,
"data": "UserId",
"render": function (data, type, full, meta) {
return "<button id='"+ data +"'>Click!</button>";
},
"autoWidth": true
}
The data property will be containing UserId in it which can be used in the render function.
You can refer to the documentation of it here

Send more values via URL

I am using Datatable plug-in to print values from database.
I get results and it prints in table. Now I am having trouble with sending values to the other file. Values that I need to send are userID, all titles of column except for last title, and two other variables which contains date.
When I click on '', beside data that contains userId, I need to send "User, Work time, Additions, Business, Break" as well as two variables printed below.
Other two variables are:
var date1 = "2017-01-01";
var date2 = "2017-02-28";
$('#myData').DataTable( {
data: dataSet,
fixedHeader: true,
responsive: true,
"columns": [
{ title: "User", data: "ime"},
{ title: "Work time", data: "Rad" },
{ title: "Additions", data: "Privatno" },
{ title: "Business", data: "Poslovno" },
{ title: "Break", data: "Pauza" },
{
"title": '<i class="icon-file-plus"></i>',
"data": "userID",
"render": function (data) {
return '' + '<i class="icon-file-plus"></i>' + '';
}, "width": "1%",
}
]
,"columnDefs": [ { "defaultContent": "-", "targets": "_all" },{ className: "dt-body-center", "targets": [ 5 ] } ]
});
Any help or advice is appreciated, I am stuck here.

Categories

Resources