dataTables not formatted on Page refresh - javascript

I have recently started working on datatables and have so far with help from some genues in the community been able to get to a point in my code so far. The issue I have is
1: when I refresh my browser, because it takes few seconds to display the datas, the table headings all appears to be merged together
2: Also I am using datatables v1.10.x and i tried using the new APIs like alertTable.clear().draw(); instead of dataTable().fnClearTable(); but I am getting alertTable.clear is not a function. I noticed changing from dataTable to DataTable seems to have an effect but it still does not work.
Any help will be much appreciated as I am still new to this plugin.
Code:
<script type="text/javascript" charset="utf-8">
var red=0;
var orange=0;
$(document).ready(function (){
setInterval (function(){
$.getJSON("ajax/maint1_json.txt", function (pcheckdata){
<!-- ------------------- Extract all Alerts ---------------------- -->
if (!$.fn.DataTable.isDataTable('#alert-table')) {
$('#alert-table').dataTable({
"bInfo": false,
"bJQueryUI": true,
"bPaginate": false,
"bLengthChange": false,
"bFilter": false,
"data": pcheckdata.alerts,
"aaSorting": [[ 3, "desc" ]],
"columns": [
{ "mData": "source" },
{ "mData": "host" },
{ "mData": "description" },
{ "mData": "value" }
],
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
if ( aData.value == "5" )
{
$('td', nRow).css('background-color', 'Red');
red++;
}
else if ( aData.value == "4" )
{
$('td', nRow).css('background-color', 'Orange');
orange++;
}
},
"aoColumnDefs": [
{
"targets": [ 0 ],
"visible": false,
"searchable": false
},
{
"targets": [ 3 ],
"mRender": function( data, type, full ) {
if (data == "0") {
return '<input class="button" type="button" id="ack-action" value="Acknowledge Alert" onclick="<-- call a function to modify value -->;">';
}
return data;
}
}
],
<-- if json value is null or empty -->
'fnServerData': function (sSource, aoData, fnCallback) {
$.ajax ({
'dataType': 'json',
'type': 'POST',
'url': sSource,
'data': aoData,
'success': fnCallback
});
},
"fnDrawCallback": function ( oSettings ) {
$('.alertcount-red').empty().append(red);
$('.alertcount-orange').empty().append(orange);
red=0;
orange=0;
}
});
} else
{
$('#alert-table').dataTable().fnClearTable();
$('#alert-table').dataTable().fnAddData(pcheckdata.alerts);
$('#alert-table').dataTable().fnAdjustColumnSizing();
}
if (!$.fn.DataTable.isDataTable('#error-table')) {
<!-- ------------------- Extract all Errors ---------------------- -->
$('#error-table').dataTable({
"bInfo": false,
"bJQueryUI": true,
"bPaginate": false,
"bLengthChange": false,
"bFilter": false,
"data": pcheckdata.errors,
"columns": [
{ data: 'host' },
{ data: 'description' }
],
'fnServerData': function (sSource, aoData, fnCallback) {
$.ajax ({
'dataType': 'json',
'type': 'POST',
'url': sSource,
'data': aoData,
'success': fnCallback
});
}
});
} else
{
$('#error-table').dataTable().fnClearTable();
$('#error-table').dataTable().fnAddData(pcheckdata.alerts);
$('#error-table').dataTable().fnAdjustColumnSizing();
}
});
}, 10000);
});
</script>

Related

JQuery Datatable initialization

I'm getting this error while trying to supply JSON into my DataTable:
DataTables warning: table id=myTable - Requested unknown parameter 'a' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
This is what my JSON looks like:
[{
"a": "asdsaddas",
"b": "asdasda",
"c": "0000000001",
"d": "name"
}]
When user clicks button I'm generating and showing the table with an AJAX callback:
$('#find_button').click(function() {
event.preventDefault();
if (validateAll()) {
$("#myTable").DataTable({
"lengthChange": false,
"pageLength": 20,
autoWidth: false,
serverSide: true,
processing: true,
"dataSrc": "",
"ajax": function(data, callback, settings) {
var $form = $("#my_form_id");
var jsonData = getFormData($form, data.start, data.length);
var request = $.ajax({
type: "POST",
url: "api",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jsonData),
dataType: "json"
});
request.then(function(response) {
console.log(JSON.stringify(response.data));
callback({
data: [JSON.stringify(response.data)],
recordsTotal: response.total,
recordsFiltered: response.total
})
}, failCallback);
},
columns: [{
"data": "a"
}, {
"data": "b"
}, {
"data": "c"
}, {
"data": "d"
}],
filter: false,
info: false,
ordering: false
});
$('#htmlTable').show();
}
});
I've read a lot of related questions with same bug, but still cannot make it work in my case. Maybe there is problem that DataTable is initialized before it gets response from server?

Is it possible to use Ajax success result to populate jQuery DataTable

I would like to declare my jQuery datatable without initially populating it and later when calling Ajax functions, I would like to take the results and use that as the data source for my data table, right now I am making multiple Ajax calls for the same purpose and I would like to eliminate this if possible.
$.ajax({
type: "GET",
url: "/Receiving/GetUnorderedParts",
datatype: "html",
data: { "id": button.attr("data-ponumber") },
success: function(data) {
var orderButton = $(".js-Order");
orderButton.removeClass("invisible");
tbl = $("#UnorderedDetail")
.DataTable({
"destroy": true,
"searching": false,
"ordering": false,
"lengthChange": false,
"pagingType": "full_numbers",
"paging": true,
"lengthMenu": [10, 25, 50, 75, 100],
ajax: {
url: "/Receiving/GetUnorderedParts",
data: { "id": button.attr("data-ponumber") },
datasrc: ""
},
"columnDefs": [
{
targets: -1,
className: 'dt-body-center'
}
],
columns: [
{
data: "Description"
},
{
data: "VendorPartNumber"
},
{
data: "Quantity"
},
{
data: "CartID",
render: function(data) {
return "<button class='btn btn-danger js-delete' data-cart-id=" +
data +
">Delete</button>";
}
}
] //EOColumns
}); //EODataTable
} //EOSuccess
}); //EOInnerAjax
You can call a function to build the data table on success something like:
$.ajax({
type: "GET",
url: "/Receiving/GetUnorderedParts",
datatype: "html",
data: { "id": button.attr("data-ponumber") },
success: function(data) {
var orderButton = $(".js-Order");
orderButton.removeClass("invisible");
createTable(data);
}
});
and the function can take in the array of objects and create a data table:
function createTable(dataSet)
{
$('#example').DataTable({
data: dataSet,
"aoColumns": [{
"sTitle": "Description",
"mData": "Description"
}, {
"sTitle": "VendorPartNumber",
"mData": "VendorPartNumber"
}, {
"sTitle": "Quantity",
"mData": "Quantity"
}, {
"sTitle": "CartID",
"mData": "CartID",
"mRender": function(data) {
return "<button class='btn btn-danger js-delete' data-cart- id=" + data + ">Delete</button>";
}}]
});
}
Check out a working example . It takes in an array of objects and create a datatable.

error 500 on jquery datatables search

i created a table with jquery datatables. when I want to filter my table with search bar, the browser gives me an alert DataTables warning: table id=grid - Ajax error. For more information about this error, please see http://datatables.net/tn/7.
this is my code :
$("#grid").dataTable({
"processing": true, // control the processing indicator.
"serverSide": true, // recommended to use serverSide when data is more than 10000 rows for performance reasons
"info": true, // control table information display field
"stateSave": true, //restore table state on page reload,
"searching": true,
"language": {
"url": "/translate/datatables.fa-IR.json"
},
"lengthMenu": [[10, 20, 50, -1], [10, 20, 50, "All"]], // use the first inner array as the page length values and the second inner array as the displayed options
"ajax": {
"url": serviceBase + "/Auth/Admin/SearchOrders2/",
"type": "GET",
'beforeSend': function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + localStorageService.get("authorizationData").token);
}
},
"columns": [
{ "data": "customerContact", "orderable": true },
{ "data": "isDone", "orderable": true },
{
"mRender":
function (data, type, row) {
var xxx = $scope.name1 = $filter("jalaliDateFromNow")(row["createdDate"]);
return "<span>" + $filter("jalaliDateFromNow")(row["orderCreationTime"]); +'</span>';
}, "orderable": true
},
{ "data": "totalPrice", "orderable": true },
{ "data": "count", "orderable": true },
{ "data": "description", "orderable": true },
{
"mRender": function (data, type, row) {
return '<button class="btn btn-sm btn-circle green tooltips" disabled="disabled"><i class="fa fa-check"></i><span>جزئیات</span></button>'
},
"orderable": false
}
],
"order": [[0, "desc"]]
});
which part of my code is wrong?

Highlight specific row base on content in jquery datatables

I am using jquery datatables.net and I have a table with information. In the one column I have true or false values for whether the user is active or not. I am trying to get it so when the value is false, highlight the value. Right now my code for my table settings looks like this:
//Settings for datatable
$('#userTable').DataTable({
"jQueryUI": true,
"serverSide": true,
"ajax": {
"type": "POST",
url: "/Management/StaffGet",
"contentType": 'application/json; charset=utf-8',
'data': function (data) { console.log(data); return data = JSON.stringify(data); }
},
"columns": [
{ "data": "employeeNumber" },
{ "data": "firstName" },
{ "data": "lastName" },
{ "data": "role" },
{
"data": "active",
},
{
"data": "employeeNumber",
"render": function (data, type, full, meta)
{
return 'Edit | Delete ';
}
}
],
"order": [[ 0, "asc"]],
"paging": true,
"deferRender": true,
"processing": true,
"stateSave": false,
"lengthMenu": [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]],
"pageLength": 10,
"pagingType": "simple_numbers",
"searching": false,
"createdRow": function ( row, data, index ) {
if (data[4] == "false" ) {
$('td', row).eq(5).addClass('highlight');
}
}
});`
Then my code for css is:
`<style type="text/css">
td.highlight {
font-weight: bold;
color: red;
}
</style>`
I feel like there is a problem with the setting on the column, any help is appreciated.
Try
$('#userTable').DataTable({
...
"createdRow": function( row, data, dataIndex ) {
//console.log(data[4]);
if ( data[4] == "false" ) {
//console.log($(row).find("td").eq(4).html());
$(row).find("td").eq(4).addClass( 'highlight' );
}},
...
The commented log statements are in there to check you are getting and comparing the correct data.
Tested with datatables 1.10.1

How to send form data along with jQuery DataTables data in server-side processing mode

I am trying to post form data without success and data couldn't be loaded.
How can I pass all form data with array and single textbox, combobox, etc. to fnServerdata?
table_obj = $('#group-table').dataTable({
"sAjaxSource": "URL Goes here",
fnServerData: function(sSource, aoData, fnCallback,oSettings) {
oSettings.jqXHR = $.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource+'?'+$.param(aoData),
"data": $("#frm").serializeArray(),
"success": fnCallback
} );
},
aaSorting: [[ 1, "desc" ]],
bProcessing: true,
bServerSide: true,
processing : true,
columnDefs: [{
'targets': 0,
'searchable':false,
'orderable':false,
'className': 'dt-body-center',
'render': function (data, type, full, meta){
return '<label><input type="checkbox" name="user_id[]" value="' + $('<div/>').text(data).html() + '"></label>';
}
}],
rowCallback: function(row, data, dataIndex){
// If row ID is in list of selected row IDs
if($.inArray(data[0], rows_selected) !== -1){
$(row).find('input[type="checkbox"]').prop('checked', true);
$(row).addClass('selected');
}
},
iDisplayLength: '50',
});
If you want to format the POST data, you can also format the form data using jquery .each() function. Let me use the answer above using solution #1 but with jquery .each() to format the data.
$('table').DataTable({
"ajax": {
"url": "URL HERE",
"type": "POST",
"data": function(d) {
var frm_data = $('form').serializeArray();
$.each(frm_data, function(key, val) {
d[val.name] = val.value;
});
}
}
});
Then you can just access that in PHP like:
var $data = $_POST['name'];
SOLUTION 1
Replace this:
$('#group-table').dataTable({
"sAjaxSource": "URL Goes here",
fnServerData: function(sSource, aoData, fnCallback,oSettings) {
oSettings.jqXHR = $.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource+'?'+$.param(aoData),
"data": $("#frm").serializeArray(),
"success": fnCallback
} );
},
with:
$('#group-table').dataTable({
"ajax": {
"url": "URL Goes here",
"type": "POST",
"data": function(d){
d.form = $("#frm").serializeArray();
}
},
Your form data will be in form parameter as an array of objects with parameters name and value, below is JSON representation:
"form": [{"name":"param1","value":"val1"},{"name":"param2","value":"val2"}]
SOLUTION 2
If you want to have form data as name/value pairs, see this jsFiddle for an example of alternative solution.
NOTES
There are checkboxes in your data table. Solution above will not work for form elements in the data table, because DataTable removes non-visible nodes from DOM.
How about this?
$('#group-table').DataTable( {
"processing": true,
"serverSide": true,
"bDestroy": true,
"bJQueryUI": true,
"ajax": {
"url": "url here",
"type": "POST",
"data": {
store: $('#store').val(),
month: $('#m').val(),
year: $('#y').val(),
status: $('#status').val(),
},
}
} );
then you can access the sample data above through PHP using this.
$_POST['store']
$_POST['month']
$_POST['year']
$_POST['status]
Hope that helps.

Categories

Resources