Well, I'm trying to do something for the job, where I need a Table made with the DataTables library to be constantly updating, for example, every 10 seconds.
I'm facing very boring problems, what I'm trying to do is give a Reload on API, as described on the official website here: https://datatables.net/reference/api/ajax.reload()
I'm using this:
function AutoReload1()
{
var table = $('#OperationFix').DataTable({
ajax: "data.json"
});
setInterval(function () {
table.ajax.reload();
}, 5000);
//loadOrdersFix();
//alert('Testing')
}
Then it returns the following error to me:
DataTables warning: table id=OperationFix - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3
Your code seems to be fine.
But error which you mentioned occurs when AutoReload1(); is called again somehow after its already loaded.
To resolve that you need to either add destroy: true or find out why AutoReload1() is called multiple times.
function AutoReload1()
{
var table = $('#OperationFix').DataTable({
ajax: "data.json",
destroy: true
});
setInterval(function () {
table.ajax.reload();
}, 5000);
}
Working Fiddle
Edit 1:
As per your fiddle, you have defined Datatable 2 places so add destroy:true on both place
var table = $(OperationFixTableId).DataTable({
dom: 'Bfrtip',
pageLength: 1000,
columns: columns,
data: OperationFix,
destroy: true
HTML:
<div class="container">
<table id="OperationFix" class="display" width="100%">
<tfoot>
<tr>
<th style="text-align:right"></th>
<th style="text-align:right"></th>
<th style="text-align:right"></th>
<th style="text-align:right"></th>
<th style="text-align:right"></th>
<th style="text-align:right"></th>
<th style="text-align:right"></th>
<th style="text-align:right"></th>
</tr>
</tfoot>
</table>
</div>
JS:
var OperationFixTableId = $('#OperationFix');
var refreshIntervalId = setInterval;
function AutoReload1()
{
var OperationFixTableId = $('#OperationFix').DataTable({
ajax: 'data.json',
destroy: true
});
setInterval(function () {
OperationFixTableId.ajax.reload();
}, 5000);
}
function AutoReload() {
var checkbox = document.getElementById('myonoffswitch');
if (checkbox.checked == true)
{
AutoReload1();
}
if (checkbox.checked == false)
{
clearInterval(refreshIntervalId);
}
}
I'm currently trying to do this, but when I test it I see that he tries to load my DataTable with 'data.json' what I'd like him to do is load it with what he has in the bank as I could do this, my connection is here:
function GetOrdersFix(startDate, endDate, status, type, onSuccess, onError) {
var uri = executionContext.settings.GetOrdersFix;
var data = {
startDate: new Date(startDate).toJSON(),
endDate: new Date(endDate).toJSON()
};
if (status) { data.status = status; }
if (type) { data.type = type; }
console.info('Loading orders fix from ' + uri);
//Call to server API
$.ajax({
type: 'GET',
url: uri,
data: data,
success: function (responseData, status, jqXHR) {
onSuccess(responseData);
},
error: function (jqXHR, status, errorThrown) {
onError(status + ',' + errorThrown + ',' + jqXHR.responseText);
}
});
}
Related
I have a Datatable of JQuery generated at first-page load. I am trying to refresh it according to the selected criteria from the selectlist.
My Datatable initialized first like the following code.
<table class="table table-striped table-hover" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Select All <input type="checkbox" class="checkbox" id="chkBoxAll"></th>
#foreach (System.Data.DataColumn col in Model.DataTypesTable.Columns)
{
<th> #col.Caption</th>
}
</tr>
</thead>
<tbody>
#foreach (System.Data.DataRow row in Model.DataTypesTable.Rows)
{
<tr>
<td> <input type="checkbox" class="checkbox" name="chkBox" value="#row.ItemArray[0]"></td>
#foreach (var cell in row.ItemArray)
{
<td>
#cell.ToString()
</td>
}
</tr>
}
</tbody>
</table>
<script>
$(document).ready(function() {
$('#dataTable').DataTable();
});
</script>
It initializes well at first. However, when I try to reload it on the selectlistchange event, it doesn't reload anything and displays an error like this.
DataTables warning: table id=dataTable - Requested unknown parameter 'Id' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
<script type="text/javascript">
$("#slctDeviceList").change(function () {
var selectedValue = $("#slctDeviceList option:selected").text();
$.ajax({
traditional: true,
dataType: 'html',
type: "GET",
url: '#Url.Action("GetDeviceDataTypes", "Home")',
data: { slctDeviceList: selectedValue },
success: function (result) {
console.log("Success");
console.log(result);
$("#dataTable").DataTable({
destroy: true,
data: result,
columns: [
{ data: "Id", name: "Id" },
{ data: "Data Name", name: "Data Name" },
{ data: "Description", name: "Description" },
{ data: "Device Type", name: "Device Type" }
], columnDefs: [{
"defaultContent": "-",
"targets": "_all"
}]
});
},
error: function (result) {
console.log("error");
}
});
});
</script>
Controller:
public JsonResult GetDeviceDataTypes(string slctDeviceList)
{
ChartRepository repository = new ChartRepository();
System.Data.DataTable dt = repository.GetDataTypes(slctDeviceList);
var json = this.Json(new { data = dt }/*, _jsonSetting*/);
return json;
}
My data is like below from the developer tools:
Please help me out to resolve the issue... Thanks in advance.
After long tries and losing hairs.. I have found a solution clear and add the rows again instead of destroy command. Here is the solution below.
<script type="text/javascript">
$("#slctDeviceList").change(function () {
var selectedValue = $("#slctDeviceList option:selected").text();
$.ajax({
traditional: true,
dataType: 'json',
type: "GET",
url: '#Url.Action("GetDeviceDataTypes", "Home")',
data: { slctDeviceList: selectedValue },
success: function (result) {
console.log("Success");
var dataTable = $("#dataTable").DataTable();
dataTable.clear().draw();
$.each(result, function myfunc (index, value) {
// use data table row.add, then .draw for table refresh
dataTable.row.add([
'<input type="checkbox" class="checkbox" name="chkBox" value="' + value.Id + '">',
value.Id,
value.DataName,
value.Description,
value.DeviceType
]).draw();
});
},
error: function (result) {
console.log("error");
}
});
});
</script>
Also, it is important to return a json object from the controller action.
PS. If the Json Object has an initial tag like data, you may need to change the looping value.Id to value.data.Id. But it is better to not use any tag.
public JsonResult GetDeviceDataTypes(string slctDeviceList)
{
ChartRepository repository = new ChartRepository();
System.Data.DataTable dt = repository.GetDataTypes(slctDeviceList);
JsonSerializerSettings _jsonSetting = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore };
var json = this.Json(dt , _jsonSetting);
return json;
}
I have a button for each row inside my jquery DataTable. I want when I click the button to alert the value of the first columns of the selected record.
The problem is that, with the code I have for the button, it does not work.
This is the documentation that I have followed: https://datatables.net/examples/ajax/null_data_source.html
Here is my code:
jQuery
$(document).ready(function () {
$.ajax({
type: "POST",
url: "WebService1.asmx/Bind",
dataType: 'json',
success: function (data) {
$('#datatable').DataTable({
data: data,
columns: [
{ 'data': 'CenterID' },
{ 'data': 'CenterName' },
{ 'data': 'LicenseKey' },
{ 'data': 'ExpiryDate' },
{ 'data': 'YearID' },
{ 'data': 'Date' },
// This is where I add the button
{ "defaultContent": "<button>Edit</button>"}
]
});
}
});
//This is where I make an attempt to add functionality for the button in the datatable
$('#datatable tbody').on('click', 'button', function () {
var data = table.row($(this).parents('tr')).data();
alert("The value is: " + data[0]);
});
});
HTML
<table id="datatable" class="display" style="width: 100%">
<thead>
<tr>
<th>CenterID</th>
<th>CenterName</th>
<th>LicenseKey</th>
<th>ExpiryDate</th>
<th>YearID</th>
<th>Date</th>
<th>Action</th>
</tr>
</thead>
</table>
Please assist. Thank you.
So after a lot of research, I got it. I had to change the button function.
$('#datatable tbody').on( 'click', 'button', function () {
var tr = $(this).closest('tr');
var value = $(tr).find('td').eq(0)[0].innerHTML;
alert(value);
return false;
});
If anyone has a better way of doing this, please let me know.
I have a Html table(instead of Grid control I used HTML table) having multiple rows with one drop down and one textbox control.I want auto complete function for that text box.I implemented the following code for auto complete but it is firing for only first row.The rows are added Dynamically (in jquery) its not workig for those rows.
<table class="table table-bordered table-hover datatable-highlight" id="tWDE_Items">
<thead>
<tr>
<th style="display:none">ItemId</th>
<th>Item Name</th>
<th>UOM</th>
</tr>
</thead>
<tbody>
#foreach (var Item in Model.Data_Wde_ItemGrid)
{
<tr class="datarow">
<td style="display:none">#Item.Item_Id</td>
<td>#Html.EditorFor(m => Item.Item_Name, new { htmlAttributes = new { #class = "form-control" } }) </td>
<td>#Html.DropDownListFor(m => Item.UOM_Id, new SelectList(Item.UOMDetails, "UomId", "UomName"), htmlAttributes: new { #class = "form-control", id = "UomId" })</td>
</tr>
}
</tbody>
</table>
And Jquery code which I tried is as follows.
$(function () {
$('#Item_Item_Name').autocomplete({
source: function (request, response) {
debugger;
var param = { ItemName: $('#Item_Item_Name').val() };
$.ajax({
url: "/WDE/GetAutoCompleteItemList",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
val: item.split('÷')[0],
label: item.split('÷')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
change: function (e, i) {
if (i.item) {
}
else {
$('#Item_Item_Name').val('');
$('#Item_Item_Id').val('');
}
},
select: function (e, i) {
debugger;
$('#Item_Item_Name').val(i.item.label);
$(this).closest("tr").find("td").eq(2).html(i.item.val);
},
minLength: 1
});
});
You're saying
having multiple rows with one drop down and one textbox control. I want auto complete function for that text box
and I'm also seeing
$('#Item_Item_Name').autocomplete(...
Are you giving the same id to every textbox? If so, that will not work. Ids have to be unique. Jquery will assume you have only 1 and fire/listen to events only for that 1 textbox.
Consider rewriting your JS using classes for the textbox instead.
I have a predefined datatable on my page that is populating from data with an ajax call. After these values are on the page the user needs an ability to add rows by clicking a button, kind of like an audit log. However, every time I go to add a row I get the error
"DataTables warning: table id=DataTables_Table_0 - Requested unknown
parameter 'data1' for row 2, column 0."
I have been up and down the internet and cannot figure this out. Help please.
I have the table variable defined globally so everyone has access to it
var escalationTable;
and then a function that calls my ajax to populate said table.
function populateTable(var1, var2, var3, var4, var5, var6, var7) {
$.ajax({
dataType: 'json',
//data: id,
type: 'GET',
async: false,
url: baseUrl + 'rest/partUrl/action?var1=' + var1 + '&var2=' + var2 + '&var3=' + var3 + '&var4=' + var4,
success: function (data) {
if (data) {
escalationTable = $('.escalationTable').DataTable({
data: data,
columns: [
{
data: "data1" ? "data1" : null
},
{
data: "data2" ? "data2" : null
}, {
data: "data3" ? "data3" : null
}
],
bSort: false
});
}
},
error: function (request, status, error) {
showErrorMessage(request);
}
});
}
html
<table class="table escalationTable col-md-12" style="width:100%;">
<thead>
<tr>
<th name='esId' scope="col">#</th>
<th name='esUser' scope="col">User</th>
<th name='esDate' scope="col">Date</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
and then my click looks like this
$('.assignToSelf').on('click', function () {
var rowNode = escalationTable
.row.add({
"esId": 'ffffff',
"esUser": 'dfsdfsdf',
"esDate": 'fffff'
})
.draw(false)
.node();
})
The answer to this question would be naming the fields in the add the same as the data that is going into the field. Not based on the name of the field.
$('.assignToSelf').on('click', function () {
var rowNode = escalationTable
.row.add({
"data1": 'ffffff',
"data2": 'dfsdfsdf',
"data3": 'fffff'
})
.draw(false)
.node();
})
<table class="table table-bordered table-striped table-hover datatable">
<thead>
<tr>
<th>ID</th>
<th>organisation Name</th>
<th>User name</th>
<th>Email</th>
<th>Contact No</th>
<th>IP</th>
<th>Date</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr class="success"> <td>3</td>
<td>Harshit </td>
<td>AtulSaini</td>
<td>arpitkumar#gmail.com</td>
<td>786048</td>
<td>::1</td>
<td>14/03/2015</td><td><button id="status"><span class="label label-success">Active</span></button></td></tr><tr class="none"> <td>4</td>
<td>Meghaa.co.edu</td>
<td>megha</td>
<td>meghaa16#gmail.com</td>
<td>786048</td>
<td>::1</td>
<td>14/03/2015</td><td><button id="status"><span class="label label-success">Active</span></button></td></tr>
</tbody>
</table>
Hello to all I want last if condition to execute on the server response which alters the res variable
The problem is when i put the whole if block of code in ajax success then variable "this" value get changed which disables the code to change the tr
and if i keep it outside as i have done here then the variable res gets destroyed as it is in a success function
<script type="text/javascript">
$(document).ready(function() {
$(".label").click(function() {
var idx = $(this).parents("tr").find('td:first').html();
var status = $(this).parents("tr").find('span').html();
var cname=$(this).parents('tr').attr("class");
alert(this);
$.ajax({
url : "scripts/update.php",
type : 'GET',
data : {
"status" : status,
"id" : idx
},
error : function(xhr, status, error) {
alert(error);
},
success : function(entry) {
var res = entry;
}
});
alert(status);
if (status == 'Active') {
$(this).parents("tr").removeClass(cname);
$(this).parents("tr").addClass("warning");
$(this).removeClass("label-success");
$(this).addClass("label-warning");
$(this).text("Deactive");
alert("Account Deacivated");
} else {
$(this).parents('tr').removeClass(cname);
$(this).parents('tr').addClass("success");
$(this).removeClass("label-warning");
$(this).addClass("label-success");
$(this).text("Active");
alert("Account Acivated");
}
});
});
</script>
Thanx in advance for your help...
I'm not exactly sure what you are trying to achieve (e.g. what kind of data is stored in res / entry). But maybe the following will help you:
<script type="text/javascript">
$(document).ready(function() {
$(".label").click(function() {
// store reference for later use (and to avoid creating the same object multiple times)
var item = $(this);
// use the previously stored jQuery item instead of recreating it every time with $(...)
var idx = item.parents("tr").find('td:first').html();
var status = item.parents("tr").find('span').html();
// ...
$.ajax({
url: "scripts/update.php",
type: 'GET',
data: {
"status": status,
"id": idx
},
error: function(xhr, status, error) {
alert(error);
},
success: function(entry) {
// `item` will still reference to the label you clicked on
}
});
});
});
</script>
Try this out :
...
var $this = $(this);
$.ajax({
url : "scripts/update.php",
type : 'GET',
data : {
"status" : status,
"id" : idx
},
error : function(xhr, status, error) {
alert(error);
},
success : function(entry) {
changeStatuts(entry, $this);
}
});
var changeStatuts = function(status, ele){
if (status == 'Active') {
ele.parents("tr").removeClass(cname);
ele.parents("tr").addClass("warning");
ele.removeClass("label-success");
ele.addClass("label-warning");
ele.text("Deactive");
alert("Account Deacivated");
} else {
ele.parents('tr').removeClass(cname);
ele.parents('tr').addClass("success");
ele.removeClass("label-warning");
ele.addClass("label-success");
ele.text("Active");
alert("Account Acivated");
}
};
Okay, after reading your comment, maybe something like the following could solve your problem. BUT: Your PHP code seems to be vulnerable against a sql injection
<script type="text/javascript">
$(document).ready(function() {
$(".label").click(function() {
// store reference for later use (and to avoid creating the same object multiple times)
var item = $(this);
// use the previously stored jQuery item instead of recreating it every time with $(...)
var parentRow = item.parents("tr");
var idx = parentRow.find('td:first').html();
var status = parentRow.find('span').html();
$.ajax({
url: "scripts/update.php",
type: 'GET',
data: {
"status": status,
"id": idx
},
error: function(xhr, status, error) {
alert(error);
},
success: function(status) {
if (status == 'Active') {
parentRow.removeClass(cname);
parentRow.addClass("warning");
item.removeClass("label-success").addClass("label-warning").text("Deactive");
alert("Account Deacivated");
} else {
parentRow.removeClass(cname);
parentRow.addClass("success");
item.removeClass("label-warning").addClass("label-success").text("Active");
alert("Account Acivated");
}
}
});
});
});
</script>