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();
})
Related
I just recently learned Django/ajax/datatables. I can project my data using a {%for%} loop and im trying to do the same thing with ajax calls.
My view:
def is_ajax(request):
return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
def getfromServer(request):
if is_ajax(request=request) and request.method == "GET":
books= Book.objects.all()
bookserial = serializers.serialize('json', books)
return JsonResponse(bookserial, safe=False)
return JsonResponse({'message':'Wrong validation'})
index.html
<div class="container">
<table id="books" class="display" style="width:100%">
<thead>
<tr>
<th>Book</th>
<th>Author</th>
<th>Genre</th>
<th>Date Publishedd</th>
<th>Copies</th>
</tr>
</thead>
</table>
</div>
<script>
$(document).ready(function() {
$('#books').DataTable({
ajax: {
type: "GET",
datatype : 'json',
url: 'views/getfromServer',
},
columns: [
{ data: 'name' },
{ data: 'author' },
{ data: 'genre' },
{ data: 'pub_date' },
{ data: 'copies' },
]
});
</script>
Im pretty sure it kinda works this way but i just cant figure it out .
jQuery DataTable is a powerful and smart HTML table enhancing plugin provided by jQuery JavaScript library
So it doesn't make sense to put an ajax request inside the .DataTable() method
You have to make the ajax request first:
$.ajax({
type: "GET",
datatype : 'json',
url: 'views/getfromServer',
success: function (result) { // result is the response you get from the server if successful
// Use the data in result to write the values to your html table respectively here
}
error: function (err) {
// handle error
}
})
thats what I came up with but still doesnt seem to do the trick all i get is an empty table .
$.ajax({
type: "GET",
datatype : 'json',
url: "views/getfromServer", // "{% url 'index' %}"
success: function (response) {
var instant = JSON.parse(response[books]);
for book in books {
var fields= instant[book]["fields"];
$("#books tbody").prepend(
`<tr>
<td>${fields["name"]||""}</td>
<td>${fields["author"]||""}</td>
<td>${fields["genre"]||""}</td>
<td>${fields["pub_date"]||""}</td>
<td>${fields["copies"]||""}</td>
</tr>`
)
}
},
error: function (response) {
alert(response["responseJSON"]["error"]);
}
})
$(document).ready(function() {
$('#books').DataTable();
I am running into the following error trying to load DataTables Objects data (https://datatables.net/manual/data/):
DataTables warning: table id=report-table - Requested unknown parameter 'PageId' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/
Below is example json data I am recieving from my C# SchemaReport/GetReportJson controller and being used in JQuery ajax success callback to initialize my DataTables:
[{"PageId":"foo","SchemaName":"foo","Name":"foo","LastModified":"foo","LastModifiedUser":"foo"}]
DataTables HTML:
<table id="report-table" class="display nowrap" style="width:100%">
<thead>
<tr>
<th>Page ID</th>
<th>Schema</th>
<th>Name</th>
<th>Last Modified</th>
<th>Last Modified User</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Page ID</th>
<th>Schema</th>
<th>Name</th>
<th>Last Modified</th>
<th>Last Modified User</th>
</tr>
</tfoot>
</table>
JQuery ajax and DataTables init script:
<script>
$(function () {
$("button#report-form-submit").click(function () {
event.preventDefault();
var data = $("form#report-form").serialize();
$.ajax({
type: "POST",
url: "#Url.Action("GetReportJson", "Report")",
data: data,
dataType: "json",
beforeSend: function (data) {
},
success: function (data) {
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
data: data,
columns : [
{
data : 'PageId'
},
{
data : 'SchemaName'
},
{
data : 'Name'
},
{
data : 'LastModified'
},
{
data : 'LastModifiedUser'
}
],
dom: 'Bfrtip',
buttons: [
{
extend: 'csv',
text: 'Download CSV',
filename: 'report-file'
},
{
extend: 'excel',
text: 'Download Excel',
filename: 'report-file',
title: ''
},
]
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
});
});
</script>
I noticed that after acknowledging the error DataTables loads as following and stating 134 entries:
134 matches the character count of the json data (provided in answer). For some reason it appears DataTables is not seeing the json object and parsing individual characters? Just not sure why it would be doing this?
Your columns block should be:
columns : [
{
'data' : 'PageId'
},
{
'data' : 'SchemaName'
},
{
'data' : 'Name'
},
{
'data' : 'LastModified'
},
{
'data' : 'LastModifiedUser'
}
],
You should also be sending your data from the Controller like this:
return Json(schemaData);
You do not need to serialize your data when you are returning a JSON since this will already return data in JSON format and if you use JsonConvert.SerializeObject then you are converting it twice which the DataTable plugin does not like.
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;
}
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);
}
});
}
$(document).ready(function () {
var url = 'http://www.json-generator.com/api/json/get/cbEfqLwFaq?indent=2';
var table = $('#example').DataTable({
'processing': true,
'serverSide': true,
'paging': false,
'bFilter': false,
'ajax': {
type: 'POST',
'url': url,
'data': function (d) {
return JSON.stringify( d );
}
}
});
table.column( 3 ).data().unique();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://cdn.datatables.net/1.10.9/css/jquery.dataTables.css" rel="stylesheet"/>
<script src="http://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Position</th>
<th>Office</th>
</tr>
</thead>
</table>
I am trying to use datatable unique function but I am unable to execute it. Actually I want to remove the duplicate data I am using dynamic ajax data.
table
.column( 3 )
.data()
.unique();
Like in this example I want to filter out the cities, Kindly suggest me what I am doing wrong and is there any other way, I couldnt found any other answers in stackoverflow or may be unable to understand. I am using version 1.10.9
Take notice of the actual purpose of unique :
Create a new API instance containing only the unique items from a the
elements in an instance's result set.
Unique returns a filtered set of unique items, it does not filter the rows shown in the table. Since you want to show rows where duplicated data is removed I will suggest you filter out the duplicates in the dataSrc callback. You do not provide details about the JSON, but here is an example with one of the "canonical" JSON datasets, where duplicated offices is filtered out. It simply uses javascripts Array.filter on the returned data array :
var table = $('#example').DataTable({
ajax: {
url: 'https://api.myjson.com/bins/avxod',
dataSrc: function(json) {
var offices = [];
return json.data.filter(function(item) {
if (!~offices.indexOf(item.office)) {
offices.push(item.office);
return item;
}
})
}
},
columns: [
{ data: 'name' },
{ data: 'position' },
{ data: 'office' },
{ data: 'salary' }
]
})
demo -> http://jsfiddle.net/cbcqdj7h/
Execute unique there just return nothing.
If you just want get a unique data after you get real data.
var table = $('#example').DataTable({
...,
drawCallback:function(){
var a = table.column( 3 ).data().unique();
console.log(a);
}
})
If you want filter data without the same value.
var table = $('#example').DataTable({
'processing': true,
'serverSide': true,
'paging': false,
'bFilter': false,
'ajax': {
type: 'POST',
'url': url,
'data': function (d) {
// TODO do some thing here to filter value
return JSON.stringify( d );
}
}
});
And DataTable doc https://datatables.net/reference/option/ajax