Im using Jquery datatable to draw a table from an API.And I want to reload the table without getting the re initializing error(only table data if possible) in every 5 seconds.Here is my Code.
var ajax_call$ = function () {
$('#example').DataTable({
"ajax": {
"url": "https://api.coinmarketcap.com/v1/ticker/",
"dataSrc": ""
},
"columns": [
{ "data": "rank" },
{ "data": "name" },
{
"data": "market_cap_usd", render: function (data, type, row) {
return '$' + data;
}
},
{
"data": "price_usd", render: function (data, type, row) {
return '$' + data;
}
},
{
"data": "24h_volume_usd", render: function (data, type, row) {
return '$' + data;
}
},
{ "data": "available_supply" },
{ "data": "percent_change_24h" }
]
});
};
$(document).ready(function () {
ajax_call$();
});
Try this,
2 things,
One change
setInterval( function () {
table.ajax.reload();
}, 5000 );
to
setInterval( submitData , 5000 );
and
table=$('#table').dataTable({
"pagingType" : 'full_numbers',
destroy: true, //ADD DESTROY TRUE
.
.
.
..
Try this,
setInterval( function () {
$("#example").DataTable().ajax.reload();
}, 5000 );
You can try this
window.setInterval(function(){
$("#TableID").DataTable().ajax.reload()
},5000);
Related
I have datatable that is being reloaded on every 5 minuts using ajax.reload().
This table has a row named as CIP.
Now on each reload I want to highlight the CIP row where value is unchanged from last value.(Value received on previous ajax call).
function getSkillStats() {
table = $('#example').DataTable( {
"ajax": {
"type" : "GET",
"url" : "../SkillStateManagement",
"dataSrc": function ( json ) {
//Make your callback here.
return json.data;
}
},
colReorder: true,
scrollY: "600px",
scrollX: false,
scrollCollapse: true,
paging: false,
select: true,
'columnDefs': [
{ width: 50, targets: 0 },
{ width: 50, targets: 1 },
{
'targets': 0,
'checkboxes': {
'selectRow': true
}
}
],
fixedColumns: true,
processing:true,
"language": {
"loadingRecords": ' ',
processing: '<i class="fa fa-spinner fa-spin fa-3x fa-fw"></i><span class="sr-only">Loading..n.</span> '
},
columns: [
{ "data" : "calls_Failed" },
{ "data" : "queuer_Threads" },
{ "data" : "calls_In_Progress" },
{ "data" : "skill_Id" },
{ "data" : "calls_Connected" },
{ "data" : "sys_Busy" },
{ "data" : "max_Cip" },
{ "data" : "queuer_name" }
]
} );
}
$(document).ready(function () {
getSkillStats();
setInterval(function () {
table.ajax.reload();
}, 300000);
} );
you can use row callback https://datatables.net/reference/option/rowCallback
The idea, is that you store the previous call and then use the row callback to check if data was unchanged (based on skillId you check the previous Cip value), then if it is you add some special class like "unchanged" ...
$('#example').dataTable( {
....
"rowCallback": function( row, data ) {
if (unchangedCid(data[4], data[7]) ) {
$('td:eq(7)', row).addClass("unchanged"); // unchanged should be defined in css
}
}
} );
and with function unchangedCid like :
var unchangedCid = function(id, cid) {
// search logic goes in search function ...
if(search(id) = cid) {
return true;
}
return false;
}
I have a jquery autocomplete that once a value is selected it loads a datatable with checkbox from an ajax call. Then while submitting the form I need to access the datatable variable to iterate each row to get the selected ones, but the datatable variable appears as undefined.
I'm doing the same as in this example, only difference is the data is coming from an Ajax request.
Can you please help me understand why is that happening?
$(document).ready(function() {
var campId;
var t_OmnitureCode;
// Campaign input autocomplete
$("#campaign").autocomplete({
source: function(request, response) {
$.ajax({
url: "promotion",
type: "GET",
data: {
term: request.term,
action: "searchCampaign"
},
dataType: "json",
success: function(data) {
if (!data.length) {
var result = [{
label: "no match found",
value: "-1"
}];
response(result);
} else {
response($.map(data, function(item) {
return {
label: item.name,
value: item.campaignId
}
}));
}
}
});
},
select: function(event, ui) {
event.preventDefault();
campId = ui.item.value;
if (campId != "-1") {
this.value = ui.item.label;
// This will apply datatables getting the content from an Ajax call
t_OmnitureCode = applyDataTableOmnitureCode(campId);
}
},
focus: function(event, ui) {
event.preventDefault();
this.value = ui.item.label;
}
});
// Handling form submission
$("#frm_promotion").on("submit", function(e) {
var form = this;
// Variable for datatable "t_OmnitureCode" is undefined below
var rows_selected = t_OmnitureCode.column(0).checkboxes.selected();
EDIT:
Just realized that even while assigning the variable (t_OmnitureCode = applyDataTableOmnitureCode(campId);) it is undefined, not sure why.
Here is the applyDataTableOmnitureCode code:
function applyDataTableOmnitureCode(campId) {
$("#tbl_omnitureCode").DataTable({
destroy: true,
scrollX: true,
fixedColumns: {
leftColumns: 1
},
"ajax": {
"url": "promotion",
"type": "GET",
"data": {
action: "searchOmnitureCodesByCampaignId",
campaignId: campId
},
"dataSrc": ""
},
"columns": [
{ "data": "key" },
{ "data": "omnitureCode" },
{ "data": "urlAppName" },
{ "data": "language" },
{ "data": "channel" },
{ "data": "createDateTime", "defaultContent": "" },
{ "data": "updateDateTime", "defaultContent": "" }
],
"columnDefs": [
{ "targets": 0, "checkboxes": { "selectRow": true } }
],
"select": {
"style": "multi"
},
"order": [[1, "asc"]],
"fnInitComplete": function() {
$("#omnitureCodeSection").show();
}
});
};
You may need to grab your DataTables object into a variable before using that:
var t_OmnitureCode = $("#tbl_omnitureCode").DataTable();
var rows_selected = t_OmnitureCode.column(0).checkboxes.selected();
And, by the way, your method of populating DataTable with external ajax-call is suboptimal. There's an ajax option for that purpose where you can specify all the necessary parameters and get better integration with DataTables API and better performance (as you don't really need to destroy and create your DataTable upon each refresh).
You would simply need to trigger .ajax.reload() whenever you need to refresh your table data.
It's a matter of scope : You declare the variable table inside $(document).ready function.
You may want to put it outside in the global scope :
var table;
$(document).ready(function() {
table = $('#example').DataTable({
...
});
The error message is as below:
Requested unknown parameter 'emPONumber' for row 0, column 0
But emPONumber is in the JSON, why datatables still prompt this error?
<script type="text/javascript">
$(document).ready(function () {
var tableId = 'tablePurchaseOrders';
var table = $('#' + tableId).DataTable({
"processing": true,
"serverSide": true,
"ajax": {
url: 'http://localhost/ControlTower2WebAPI/api/PurchaseOrder/GetAllUploadedPurchaseOrders',
type: 'GET',
data: function (data) {
//debugger;
var model = {
draw: data.draw,
start: data.start,
length: data.length,
columns: data.columns,
search: data.search,
order: data.order
};
return model;
},
failure: function (result) {
debugger;
alert("Error occurred while trying to get data from server: " + result.sEcho);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
alert("Error occurred while trying to get data from server!");
},
dataSrc: function (json) {
var _data = JSON.stringify(json.Data);
debugger;
return _data;
}
}
,
"columns": [
{ "data": "emPONumber", title: "emPONumber" },
{ "data": "ASMPONumber", title: "ASMPONumber" },
{ "data": "material", title: "material" }
]
});
});
</script>
json in dataSrc: function (json):
{"ContentEncoding":null,"ContentType":null,"Data":{"draw":1,"recordsTotal":1,"recordsFiltered":1,"data":[{"emPONumber":"EM1234567","ASMPONumber":"A741000013","material":"26-00010","quantity":5,"UOM":"EA","asmPOQuantity":5,"createBy":"m","ASMPOYear":2018,"ASMPOMonth":6,"ASMPOVendor":"10008"}]},"JsonRequestBehavior":1,"MaxJsonLength":null,"RecursionLimit":null}
json (_data) return by ajax in dataSrc:
{
"draw":1,
"recordsTotal":1,
"recordsFiltered":1,
"data":
[{
"emPONumber":"EM1234567",
"ASMPONumber":"A741000013",
"material":"26-00010",
"quantity":5,
"UOM":"EA",
"asmPOQuantity":5,
"createBy":"m",
"ASMPOYear":2018,
"ASMPOMonth":6,
"ASMPOVendor":"10008"
}]
}
Try
dataSrc: function (json) {
for(key in json.Data){ json[key] = json.Data[key]; }
delete json['Data'];
return json.data;
}
I have a datatable and I want, when I click some row I get row id and go back to the controller and uptade some data by the row id. I am getting row id(data.SiparisID) BUT I cant send data to controller`#section scripts{
<script>
$(document).ready(function () {
});
$("#SiparisTable").DataTable({
"ajax": {
"url": "/Goster/getList",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "SiparisID" },
{ "data": "SiparisAd" },
{ "data": "SiparisModel" },
{ "data": "SiparisTur" },
{ "data": "SiparisAdet" },
{ "data": "SiparisTarih" },
{ "data": "SiparisDurum" },
{
"data": "SiparisID", "render": function () {
return "<input type='submit' value='Güncelle' class='btn btn-default' onclick='backoperation()' />"
}
}
]
});
var table = $('#SiparisTable').DataTable();
$('#SiparisTable tbody').on('click', 'tr', function () {
var data = table.row(this).data();
alert('You clicked on ' + data.SiparisID + '\'s row');
});
</script>
<script>
function backoperation() {
window.location.href = "#Url.Action("Index", "Guncelle")";
}
</script>
}
`
function backoperation() {
window.location.href = "#Url.Action("Index", "Guncelle")?param=obj";
}
this case it redirect to another page
or
you can make request through Ajax request
"ajax": {
"url": "/Goster/getList??param=obj",
"type": "GET",
"datatype": "json"
},
then it come in your controller
this case it updated in same view
var table = $('#SiparisTable').DataTable();
$('#SiparisTable tbody').on('click', 'tr', function () {
var data = table.row(this).data();
alert('You clicked on ' + data.SiparisID + '\'s row');
$.ajax({
url: '/Guncelle/Process',
type: 'GET',
data: {
id: data.SiparisID,
success: function () { },
error: function () { }
}
});
});**THE VIEW**
public ActionResult Process(int id)THE CONTROLLER
{}
I found this and this work for me. I can get the id in the script with this controller
I m using jquery datatables in many pages and its working good in every page and in a single page its not working properly, i mean when i use tab to go through datatable, it works fine for the first time and when i try to do the same for second time, if i try to focus on any thing in few seconds in data table, the focus disappears and the foucs starts from the starting of the page.
Here goes the code
function tableCall(){
var clientId = $('#clientId').val();
var versionCount = $('#versionCount').val();
var fromDate = $('#fromDate').val();
var toDate = $('#toDate').val();
$.ajax({
url: auditTrail.props.reporttableURL,
type: "POST",
dataType: "json",
data: {
clientId:clientId,
versionCount:versionCount,
fromDate:fromDate,
toDate:toDate
},
success: function (data) {
searchJSON = data.data;
var len=searchJSON.length;
if (len > 0){
$('.no-data, #warning-sign').hide();
createTable();
}else{
$('.no-data').hide();
$('#warning-sign').show();
}
}
});
}
function createTable() {
wwhs.setADAAttrDynamic($('#auditTable'));
if ($.fn.DataTable.isDataTable('#auditTable')) {
// table.destroy();
$("#auditTable tbody").empty();
}
table = $('#auditTable').dataTable({
"searching":false,
"destroy":true,
"autoWidth": false,
"ordering": true,
"destroy":true,
"stateSave": true,
"drawCallback": attachEvents,
"stateLoadParams": function (settings, data) {
return false;
},
data: searchJSON,
columns: [{
data: "reportName"
}, {
data: "reportStatus"
}, {
data: "timeStamp"
}, {
data: "requestedBy"
}],
"columnDefs": [{
"render": function (data, type, row) {
if(row.reportStatus.toUpperCase() == 'PROCESSED')
return '<a class="blue-text" " data-name="'+ row.reportName +'">' + row.reportName + '</a>';
else
return row.reportName;
},
"width": "50%",
"targets": 0
}, {
"width": "15%",
"targets": 1
}, {
"width": "20%",
"targets": 2
}, {
"width": "15%",
"targets": 3
}]
});
}
I think the problem is because the datatable instance is not destroyed.
Since datatables saves all the nodes into an object and renders it when ever it wants, emptying the tbody doesnt do anything. it just removes the elements in the page which can be re-drawn/re-rendered by datatable from its stored object.
You can check if the object is already initialized and the destroy it before re-initializing.
if(typeof table != "undefined")
table.destroy();
So the final code will look something like
function tableCall(){
var clientId = $('#clientId').val();
var versionCount = $('#versionCount').val();
var fromDate = $('#fromDate').val();
var toDate = $('#toDate').val();
$.ajax({
url: auditTrail.props.reporttableURL,
type: "POST",
dataType: "json",
data: {
clientId:clientId,
versionCount:versionCount,
fromDate:fromDate,
toDate:toDate
},
success: function (data) {
searchJSON = data.data;
var len=searchJSON.length;
if (len > 0){
$('.no-data, #warning-sign').hide();
createTable();
} else {
$('.no-data').hide();
$('#warning-sign').show();
}
}
});
}
function createTable() {
wwhs.setADAAttrDynamic($('#auditTable'));
if ($.fn.DataTable.isDataTable('#auditTable')) {
if(typeof table != "undefined")
table.destroy();
}
table = $('#auditTable').dataTable({
"searching":false,
"destroy":true,
"autoWidth": false,
"ordering": true,
"destroy":true,
"stateSave": true,
"drawCallback": attachEvents,
"stateLoadParams": function (settings, data) {
return false;
},
data: searchJSON,
columns: [{
data: "reportName"
}, {
data: "reportStatus"
}, {
data: "timeStamp"
}, {
data: "requestedBy"
}],
"columnDefs": [{
"render": function (data, type, row) {
if(row.reportStatus.toUpperCase() == 'PROCESSED')
return '<a class="blue-text" " data-name="'+ row.reportName +'">' + row.reportName + '</a>';
else
return row.reportName;
},
"width": "50%",
"targets": 0
}, {
"width": "15%",
"targets": 1
}, {
"width": "20%",
"targets": 2
}, {
"width": "15%",
"targets": 3
}]
});
}