JQuery Datatables not load immediately/disable autolaod - javascript

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();
});

Related

pass json data collectio into DataTable

I trying to insert json collection in datatable using jQuery.
This is my code:
function reloadseekers(vacancy){
if (vacancy) {
$.ajax({
url: '/getseekers/' + vacancy,
method: "GET",
dataType: "json",
cache: false,
success: function (data) {
$.each(data.appseekers, function (index) {
$('#evaluated_list_table').dataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": true,
"data": data.appseekers,
"columns": [
{ "title": "SSN" },
{ "data": data.appseekers[index].ssn},
{ "title": "Full Name" },
{ "data": data.appseekers[index].first_name + ' '+data.appseekers[index].second_name +' '+data.appseekers[index].middle_name+' '+data.appseekers[index].last_name },
{ "title": "Primary phone" },
{ "data": data.appseekers[index].phone_1},
{ "title": "Secondary phone " },
{ "data": data.appseekers[index].phone_2},
{ "title": "Secondary phone " },
{ "data": data.appseekers[index].evaluation.total_evaluation},
]
});
});
}
}
}
The table empty and without any data,,, the json data is already gotten from the server:
The json data from the server
what is wrong in this code? help please

How do I Link a TD in dataTable?

I have a function like this. How do I hyperlink specific columns? Lets say I want to have the Download FIle render like this Download File And where uploadFile/file is the path of my download link. When I try to run this function, it not fill the table. Could you guys help me out?
function tabela() {
var table = $("#example1").DataTable({
"ajax": "pages/forms/request.php",
"columns":
[
{ "data": "ID" },
{ "data": "SERIAL_NUMBER" },
{ "data": "AUDITOR" },
{ "data": "FALHA" },
{
"data": "ARQUIVO",
"fnCreatedCell": function(nTd, sData, oData, iRow, iCol) {
$(nTd).html("<a href='uploadFiles/" + oData.ARQUIVO + "'>Download File</a>");
},
{ "data": "DATA" },
]
}
);
}
tabela();

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>

Ajax request don't start immediately

How can i stop this from autoplaying, I have a search button and I want to search first before getting the data, any approach is okay to me, whether it's AJAX side or Javascript side, please help.
Javascript
var table = $('#SARDatatable').DataTable({
"processing": true,
dom: "<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-2'i><'col-sm-5'B><'col-sm-5'p>>",
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5',
'print'
],
"ajax": {
"url": '/Home/GetAllSAR',
"type": "POST",
"datatype": "json",
"data": function (d) {
d.searchParameters = {};
d.searchParameters.sarcode = $('#txtSAR').val();
d.searchParameters.stype = $('#txtSType').val();
}
},
"columns": [
{ "data": "sarcode", "autoWidth": true },
{ "data": "stype", "autoWidth": true },
{ "data": "amount", "autoWidth": true },
{ "data": "filterno", "autoWidth": true }
]
});
$('#btnSearch').on("click", function () {
table.ajax.reload();
});
If I understand you correctly, you would like to only initialize the table after a button has been clicked, so that the AJAX request to get the data will not be issued before clicking the button.
If this is the case, then I would suggest the following:
Have a button that inits the table:
HTML
<button id='initTable'>Init Table</button>
JavaScript
var table;
$('#initTable').on('click', function() {
table = $('#SARDatatable').DataTable({ // code to init the DataTable });
});
Have the 'reload' button
HTML
<button id='btnSearch'>Reload</button>
JavaScript
$('#btnSearch').on("click", function () {
table.ajax.reload();
});
After you init the table, you can hide the "Init Table" button, so that there will be only one button at a time.
Hope this helps.

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

Categories

Resources