Jquery Data tables Date format [duplicate] - javascript

This question already has answers here:
ASP.NET MVC JsonResult Date Format
(25 answers)
Closed 3 years ago.
I am trying to pull date in my data tables but for some reason the format of the data is not correct. I am getting the data from a stored procedure.
Original:
/Date(1575612000000)/
Expected Output:
01-15-2020
Code example:
$(document).ready(function () {
var mesa = $('.datatable').DataTable({
filename: "LocationCodes",
responsive: true,
"bAutoWidth": false, // toggle this depending on how wide you want the table
"ajax": {
"url": "/controller/sp",
"type": "GET",
"datatype": "json"
},
"deferRender": true,
"responsive": true,
dom: 'Bfrtip',
"bSort": false,
buttons: [
'excel', 'print'
],
"columns": [
{ "data": "FileName" },
{ "data": "ProjectName" },
{ "data": "RecordInsertTime" }
]
Thanks,
Minhal

is this what you want?
var d = new Date(1575612000000);
let month=d.getMonth()+1 // 12
let date=d.getDate() // 6
let year=d.getFullYear()
console.log(`${date}-${month}-${year}`)

Related

Refresh buttons on paginate [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
DataTable cannot click the button after pagination
(1 answer)
datatables jquery click event not working after pagination
(7 answers)
Closed 3 years ago.
I am building a paginated Datatable from ajax-sourced data:
let table = $('#userTable').DataTable({
destroy: true,
"ajax": {url: url, type: 'GET', "dataSrc": ""},
"pagingType": "simple",
"columnDefs": [
// ...
],
"order": [[3, "desc"]],
"columns": [
{ "data": "view", "defaultContent": "" },
{ "data": "username" },
{ "data": "email", "defaultContent": ""},
{ "data": "lastActive"},
{ "data": "completed" },
{ "data": "_id" }
],
"fnInitComplete": function(oSettings, json) {
console.log("Finished drawing table");
$('#spinner').addClass('d-none');
$('.view-profile').on('click', getProfile);
$('.btn-delete').on('click', purgeUser);
$('.page-link').on('click', () => {
console.log("Clicked on paginate button")
$('.view-profile').on('click', getProfile);
$('.btn-delete').on('click', purgeUser);
})
}
});
I add buttons (.view-profile and .btn-delete) to each row, and add a listener only after the table is initialised using [fnInitComplete][2].
However, on clicking on a paginate button .page-link, the buttons are no longer clickable - how can I re-listen for clicks on paginating?
I've tried adding a timeout function to first wait for buttons to be drawn (.view-profile) and then wait for 1s after clicking on a .page-link before adding $('.view-profile').on('click', getProfile) - but this isn't working. What am I missing?
if($('.view-profile')){
setTimeout(() => {
$('.page-link').on('click', function() {
setTimeout(() => {
console.log("Next page")
$('.view-profile').on('click', getProfile);
$('.btn-delete').on('click', purgeUser);
}, 1000);
})
}, 1000);
}

DataTable Processing Error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm working on loading a new datatable when the user clicks on a button. The new datatable is populated by a server side script. When the user clicks on the button the datatable hangs and says "Processing".
$('#QuerySelectedBtn').on('click', function(event) {event.preventDefault();
$("#example").dataTable().fnDestroy();
var table = $('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax":{
url: './datasource02.php',
type: 'get',
error: function(){ // error handling
$(".example-error").html("");
$("#example").append('<tbody class="example-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#example_processing").css("display","none");
}
},
"columns": [
{ "data": "ID" },
{ "data": "user_id" },
{ "data": "option_name" },
{ "data": "option_value" }
],
"order": [],
"dom": 'lfrtipB',
"buttons": {
"dom": {
"button": {
"tag": "button",
"className": "btn"
}
},
"buttons": [
{ extend: 'copy', text: 'Copy' },
{ extend: 'csv', text: 'CSV' },
{ extend: 'excel', text: 'Excel' },
{ extend: 'pdf', text: 'PDF' },
{ extend: 'print', text: 'Print' }
]
}
});
});
Solution : Instead of using this line $("#example").dataTable().fnDestroy(); use below code
var table = $('#example').DataTable();
table.destroy();
Reason :
1. $("#example").dataTable();` // .fnDestroy() works
2 . $("#example"). DataTable();' // .fnDestroy() doesn't work
//.destroy(); will work
Problem in your current configuration :
Your using this API : dataTable().fnDestroy(); this will not work with DataTable(); api
For reference : https://datatables.net/reference/api/

Jquery Datatables Checkbox selected append to input field

the btnSearchName will open a Modal with table of the search result, then it has checkbox per row to select, then after I click the btnSubmit, the Modal will close and must put the selected ssn_or_tin column in an input field like '123, 645, 936, 743', I already tried many codes but not working, please help
$('#btnSearchName').on("click", function() {
Namestable = $('#NamesDatatable').DataTable({
"processing": true,
'select': {
'style': 'multi'
},
'order': [[1, 'asc']],
dom: "<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-6'i><'col-sm-6'p>>",
"ajax": {
"url": '/Home/GetAllCusname',
"type": "POST",
"datatype": "json",
"data": function (d) {
d.searchParameters = {};
d.searchParameters.name = $('#txtName').val();
}
},
"columns": [
{
defaultContent: '',
className: 'select-checkbox',
'checkboxes': {
'selectRow': true
},
orderable: false
},
{ "data": "ssn_or_tin", "autoWidth": true },
{ "data": "name", "autoWidth": true }
]
});
});
$('#btnSubmit').on("click", function () {
var rows_selected = Namestable.column(0).checkboxes.selected(); //i have not tested this line of code yet if it's working,
maybe there is another way of getting the selected checkbox, maybe by their class if they have the 'selected' class
$.each(rows_selected, function () {
$('#txtSSNTIN').append(
//I don't know what code to put here, it must append the
'ssn_or_tin' values like '123, 953, 673' in the input field with
the id 'txtSSNTIN'
);
});
});
You could have try Onrowbound in DataTable. You dont have to specify these things

Why is rows() on a server-side DataTable not a function?

Why is rows() not a function on a server-side datatable?
The tables works fine beside that.
I have used rows() on five other client-side datatables before without any problems.
var tableComputerAndDevice = $('#tableComputerAndDevices').dataTable({
searching: true,
processing: true,
serverSide: true,
language: {
"processing": '<div style="background-color:#eee"> <span class="fa fa-spinner fa-pulse fa-5x"> </span> </div>'
},
ajax: {
url: url,
data: data,
type: "POST"
},
columns: [
{ "data": "checkbox", "searchable": false },
{ "data": "ComputerName", "searchable": true },
{ "data": "LastContact", "searchable": true }
]
});
var nodes = tableComputerAndDevice.rows('.selected').nodes();
console.log('nodes: ' + nodes);
Error: TypeError: tableComputerAndDevice.rows is not a function
Yes you judged it correctly. You need to change the dataTable to DataTable
Also to state that there is a difference between dataTable and DataTable.
The difference between the two is that the first will return a jQuery
object, while the second returns a DataTables API instance.
Change dataTable to DataTable. I answer my own question because I spent a hour with this bug, so I hope I can help others.
var tableComputerAndDevice = $('#tableComputerAndDevices').DataTable({

Datatables Jquery Ajax

I have an issue with the reinitialisation of my datatable. My code below works by pulling in a json from getOrderStatus.php and upon success of this puts all the json data into javascript variables and then from this i can set these variables to div tags and display the data i need on my webpage. However the Datatable cannot be reinititalised once the ajax loop runs and displays the following error message "DataTables warning: table id=mytable - Cannot reinitialise DataTable". I believe i need a way to kill the table and recreate it upon the ajax refresh however i cant seem to find a way to do this ?
$(document).ready(function ajaxLoop(){
$.ajax({
url: 'getOrderStatus.php', // Url of Php file to run sql
data: "",
dataType: 'json', //data format
success: function updateOrder(data) //on reciept of reply
{
var OrdersSubmitted = data.OrderStatus[0].SUBMITTED; //get Orders Submitted Count
var OrdersFulfilled = data.OrderStatus[0].FULFILLED; //get Orders Fulfilled count
var LastTransaction = data.LastTransaction[0]; //get Last Transaction
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#OrdersSubmitted').html(OrdersSubmitted);
$('#OrdersFulfilled').html(OrdersFulfilled); //Set output html divs
$('#mytable').dataTable({
"data": LastTransaction,
"aging": false,
"searching": false,
"columns": [
{ "title": "ORDER_ID" }, // <-- which values to use inside object
{ "title": "STATUS" },
{ "title": "ACC_NUMBER" },
{ "title": "SORT_CODE" }
]
});
setTimeout(ajaxLoop, 2000);
}
});
});
Did you try using "bDestroy": true.
$('#mytable').dataTable({
"data": LastTransaction,
"aging": false,
"searching": false,
"bDestroy": true,
"columns": [
{ "title": "ORDER_ID" }, // <-- which values to use inside object
{ "title": "STATUS" },
{ "title": "ACC_NUMBER" },
{ "title": "SORT_CODE" }
]
});
Another way is if you check if datatable is already init. on your table
var table = $('#mytable');
if ($.fn.DataTable.fnIsDataTable(table)) {
//It's already a datatable
//clear and destroy
table.dataTable().fnClearTable();
table.dataTable().fnDestroy();
}
**It seems your are using latest datatable version:**
then option should be destroy:true (aging should be changed to paging):
$('#mytable').dataTable({
"data": LastTransaction,
"paging": false,
"searching": false,
"destroy": true,
"columns": [
{ "title": "ORDER_ID" }, // <-- which values to use inside object
{ "title": "STATUS" },
{ "title": "ACC_NUMBER" },
{ "title": "SORT_CODE" }
]
});
and check on existing datatable would be:
if($.fn.DataTable.isDataTable("#myTable"))
{
$('#myTable').DataTable().clear().destroy();
}

Categories