The following code works fine for me:
$(document).ready(function () {
var t = $("#users").DataTable({
columnDefs: [{
"searchable": false,
"orderable": false,
"targets": 0
}],
order: [[1, 'asc']],
ajax: {
url: "/api/users",
dataSrc: ""
},
columns: [
{
data: "id"
},
{
data: "firstName"
},
{
data: "lastName"
},
{
data: "userName"
},
{
data: "id",
render: function (data) {
return "<a href='#'><i class='fa fa-eye js-view' data-id='" + data + "'></i></a> | <a href='#'><i class='fa fa-pencil js-edit' data-id='" + data + "'></i></a> | <a href='#'><i class='fa fa-trash js-delete' data-id='" + data + "'></i></a>";
}
}
],
Is there a way to use column indexes instead of names like this?:
$(document).ready(function () {
var t = $("#users").DataTable({
columnDefs: [{
"searchable": false,
"orderable": false,
"targets": 0
}],
order: [[1, 'asc']],
ajax: {
url: "/api/users",
dataSrc: ""
},
columns: [
{
data: 0
},
{
data: 1
},
{
data: 2
},
{
data: 3
},
{
data: 0,
render: function (data) {
return "<a href='#'><i class='fa fa-eye js-view' data-id='" + data + "'></i></a> | <a href='#'><i class='fa fa-pencil js-edit' data-id='" + data + "'></i></a> | <a href='#'><i class='fa fa-trash js-delete' data-id='" + data + "'></i></a>";
}
}
],
All I basically want to do is to be able to display the first 4 columns of a web API source or even choose which four columns to display by INDEX not by name. Is this possible?
Instead of converting the result of the AJAX call as was suggested, I implemented an "ugly hack" that proved effective. I was really surprised that my problem could not be solved conventionally by "index" so instead I created a pseudo-index that grabs the column names from data attributes in the table tag and fed it to numbered variables like this:
//Display first 4 columns of data
var f1 = $(".grid").attr("data-f1");
var f2 = $(".grid").attr("data-f2");
var f3 = $(".grid").attr("data-f3");
var f4 = $(".grid").attr("data-f4");
var f5 = $(".grid").attr("data-f5"); //this value is the same as f1
var t = $(".grid").DataTable({
columnDefs: [{
"searchable": false,
"orderable": false,
"targets": 0
}],
order: [[1, 'asc']],
ajax: {
url: "/api/users",
dataSrc: ""
},
columns: [
{
data: f1
},
{
data: f2
},
{
data: f3
},
{
data: f4
},
{
data: f5,
render: function (data) {
return "<a href='#'><i class='fa fa-eye js-view' data-id='" + data + "'></i></a> | <a href='#'><i class='fa fa-pencil js-edit' data-id='" + data + "'></i></a> | <a href='#'><i class='fa fa-trash js-delete' data-id='" + data + "'></i></a>";
}
}
],
This approach proved to be surprisingly flexible, as I could swap the display order of the column on the fly without changing the code. Still, I would have preferred the indexed approach, though.
Related
I am using a datatable in my laravel project for huge data. It's about 78000 rows and 30 columns.
I get this error :
DataTables warning: table id=dt-basic-example - Ajax error. For more information about this error, please see http://datatables.net/tn/7
When I insert smaller data everything works good and no error appears.
I went to this url : enter link description here
I do every step but it return this : This request has no response data available
What can I do?
My controller :
$ProducerCompanies = \App\ProducerCompanies::all()->where('Activation',$company);
return DataTables::of($ProducerCompanies)
->addColumn('id', function ($ProducerCompanies) {
if ($ProducerCompanies->Activation == '0') {
$data = "bg-danger" . '/' . $ProducerCompanies->id;
} elseif ($ProducerCompanies->Activation == '1') {
$data = "bg-success" . '/' . $ProducerCompanies->id;
}
return $data;
})
->addColumn('IdCategory', function ($ProducerCompanies) {
$id = $ProducerCompanies->category->name;
return $id;
})
->addColumn('action', function ($ProducerCompanies) {
$id = $ProducerCompanies->id;
return $id;
})
->addColumn('country', function ($ProducerCompanies) {
if ($ProducerCompanies->industrialname != '') {
$id = $ProducerCompanies->countryname->name . '/' . $ProducerCompanies->statename->name . '/'
. $ProducerCompanies->cityname->name . '/' . $ProducerCompanies->industrialname->name;
} else {
$id = $ProducerCompanies->countryname->name . '/' . $ProducerCompanies->statename->name . '/'
. $ProducerCompanies->cityname->name;
}
return $id;
})
->addColumn('Info', function ($ProducerCompanies) {
$data = $ProducerCompanies->Information;
return $data;
})
->addColumn('product', function ($ProducerCompanies) {
if ($ProducerCompanies->leaders->count() != 0) {
foreach ($ProducerCompanies->leaders as $row) {
if ($row->where('Activation', '1')->count() === $row->count()) {
$data2 = 'bg-success';
} else if ($row->where('Activation', '1')->count() >= 0) {
$data2 = 'bg-danger';
}
}
} else {
$data2 = 'bg-danger';
}
if ($ProducerCompanies->certificate->count() != 0) {
foreach ($ProducerCompanies->certificate as $row2) {
if ($row2->where('Activation', '1')->count() === $row2->count()) {
$data3 = 'bg-success';
} else if ($row2->where('Activation', '1')->count() >= 0) {
$data3 = 'bg-danger';
}
}
} else {
$data3 = 'bg-danger';
}
if ($ProducerCompanies->product->count() != 0) {
foreach ($ProducerCompanies->product as $row3) {
if ($row3->where('Activation', '1')->count() === $row3->count()) {
$data4 = 'bg-success';
} else if ($row3->where('Activation', '1')->count() >= 0) {
$data4 = 'bg-danger';
}
}
} else {
$data4 = 'bg-danger';
}
$data = $ProducerCompanies->id . '/' . $data2 . '/' . $data3 . '/' . $data4;
return $data;
})
->make(true);
My script in HTML page :
$(document).ready(function () {
$("#dt-basic-example").dataTable({
serverSide: true,
processing: true,
ajax: {
url: '/ProducerCompanies/ajax/{{ $company }}',
data: function (data) {
data.params = {
sac: "helo"
}
}
},
scrollY: 500,
srollX: true,
ScrollCollapse: true,
columns: [
{data: "id",className: 'id'},
{
"data": "Logo40",
name: "Logo40",
render: function (data) {
return "<div style='width: 50px;height: 50px'><img class='w-100 h-100' src='/" +
data + "'></div>"
},
orderable: false,
searchable: false
},
{"data": "Name"},
{"data": "CompanyId", searchable: false},
{
"data": "IdCategory",
name: "IdCategory",
render: function (data) {
return "<div>" + data + "</div>"
}
, searchable: false
},
{"data": "CreateTime", searchable: false},
{"data": "created_at", searchable: false},
{
"data": "action",
name: "action",
render: function (data) {
return "<div class='d-flex justify-content-center'>" +
"<div style='width: 50px;height: 35px'>" +
"<a class=\"btn btn-primary d-inline-block w-100 h-100\"\n" +
"href=\"/ProducerCompanies/index/" + data + "/edit\">" +
" <i class=\"fal fa-edit text-white\"></i></a></div>\n" +
"<div style='width: 50px;height: 35px'>" +
"<button class=\"btn btn-danger btn-sm text-white w-100 h-100 destroy ml-2\"" +
" value='" + data + "'>\n" +
"<i class=\"fal fa-trash-alt\"></i>\n" +
"</button></div></div>\n"
}, searchable: false
},
{"data": "CompanyNumber", searchable: false},
{"data": "FactoryNumber", searchable: false},
{"data": "FaxNumber", searchable: false},
{"data": "CompanyAddress", searchable: false},
{"data": "FactoryAddress", searchable: false},
{"data": "BackgroundImg", searchable: false},
{"data": "InformationImg", searchable: false},
{"data": "CompanyEmail", searchable: false},
{"data": "CompanyWebsite", searchable: false},
{
"data": "country",
name: "country",
render: function (data) {
return "<div><img class='mr-2' style='width: 25px;' src='/images/iran-flag.jpg'>" +
data + "</div>"
}
, searchable: false
},
{
"data": "Info",
name: "Info",
render: function (data) {
return "<div style='max-width: 850px''>" + data + "</div>"
}
},
{
"data": "product",
name: "product",
render: function (data) {
$data = data.split('/');
return "<a href='/product/" + $data[0] + "' " +
"class='btn btn-outline-primary float-right d-flex align-baseline'" +
" style='margin-top: 90px'>" +
"<i class='d-inline-block " + $data[3] + " rounded-circle mr-2 mt-1'" +
" style='width: 15px;height: 15px'></i>" +
"محصولات این شرکت</a>" +
"<a href='/company-leaders/" + $data[0] + "' " +
"class='btn btn-outline-primary float-right mr-2 d-flex align-baseline'" +
" style='margin-top: 90px'>" +
"<i class='d-inline-block " + $data[1] + " rounded-circle mr-2 mt-1'" +
" style='width: 15px;height: 15px'></i>" +
"مدیران این شرکت" +
"</a>" +
"<a href='/company-Certificate/" + $data[0] + "' " +
"class='btn btn-outline-primary float-right mt-2 d-flex align-baseline'>" +
"<i class='d-inline-block " + $data[2] + " rounded-circle mr-2 mt-1'" +
" style='width: 15px;height: 15px'></i>" +
"گواهی نامه های این شرکت</a>"
}
}
]
});
});
I am very new to Datatables and this might be simple, but surely I am missing something. I am trying to create a button column that uses the filename of each row and uses it to make an ajax call to display a picture on click. What I get wrong is that, every button of the column displays the same image, and not the image of the filename for each row. Here is the code:
$.ajax ({
url: "http:// ...... /Services/DBPrintDatatable?customer_id=" + projectid,
type: "GET",
dataType: 'json',
async: false,
success: function(data) {
$('#projectsdt').show();
projectsTable = $('#projectsdt').DataTable({
"pageLength": 10,
"data": data,
"scrollX": true,
"aaSorting": [],
"columns": [
{ "data": "upload_date" },
{ "data": "filename" },
{ "data": "uploader" },
{ "data": "upload_place" },
{ "data": "is_ok" },
{ "data": "custom_verdict" },
{
data: { "data": "filename" },
render: function ( data, type, row ) {
return "<a data-fancybox='gallery' class='btn btn-success' href='http://......./Services/DBShowImage?filename='+ { 'data': 'filename' }>Show</a>";
}
},
] ,
});
Thank you in advance!
If the image url required is like
http://......./Services/DBShowImage?filename=filenameFromData
Then you should generate it first inside the render like below code
href='http://......./Services/DBShowImage?filename="+ row.filename+"';
render: function ( data, type, row ) {
return "<a data-fancybox='gallery' class='btn btn-success' href='http://......./Services/DBShowImage?filename="+ row.filename+"'>Show</a>";
}
sorry for my bad english,
i want to show image in my table using datatables.
var t = $("#mytable").dataTable({
initComplete: function() {
var api = this.api();
$('#mytable_filter input')
.off('.DT')
.on('keyup.DT', function(e) {
if (e.keyCode == 13) {
api.search(this.value).draw();
}
});
},
oLanguage: {
sProcessing: "loading..."
},
processing: true,
serverSide: true,
ajax: {"url": "wisataadmincontroller/json", "type": "POST"},
columns: [
{
"data": "id_wisata",
"orderable": false
},{"data": "nama_wisata"},{"data": "alamat_wisata"},{"data": "no_telp"},{"data": "kategori"},{"data": "longitude"},{"data": "latitude"},{"data": "gambar","render": function(data, type, row) {
return '<img src="'+data+'"style="height:100px;width:100px;" />';
}},{"data": "like"},
{
"data" : "action",
"orderable": false,
"className" : "text-center"
}
],
order: [[0, 'desc']],
rowCallback: function(row, data, iDisplayIndex) {
var info = this.fnPagingInfo();
var page = info.iPage;
var length = info.iLength;
var index = page * length + (iDisplayIndex + 1);
$('td:eq(0)', row).html(index);
}
});
});
and the result :the images are empty
the images are empty because the image source only contains the images file name,
so how to use baseurl in datatables?
Just plug it in?
<img src="<?php echo base_url(); ?>'+data+'"style="height:100px;width:100px;" />
I have hosted one website in our company server.
In localhost I can access to all tables fine.
However in the hosted one when I click the link and that page contains tables gives me error:
** Message from webpage **
DataTables warning: table id=datatable-questionnaires - Ajax error. For more information about this error, please see http://datatables.net/tn/7
however I don't know how to fix this... how to solve this issue
edited:
`
var handleDataTables = function () {
var catId = $('#catId').val();
var typeId = $('#typeId').val();
$('#datatable-questions').dataTable({
"serverSide": true,
"ajax": {
"url": "handlers/_getQuestions.asp?catId=" + catId + "&typeId=" + typeId
},
"aoColumns": [
{
"bSortable": false
}
],
"fnInitComplete": function (oSettings, json) {
$('#datatable-questions_filter').append(" <button class='btn btn-sm btn-default' data-toggle='modal' data-target='#questionAddModal'>Criar Pergunta</button>");
}
});
$('#datatable-users').dataTable({
"serverSide": true,
"ajax": {
"url": "handlers/_getUsers.asp?"
},
"aoColumns": [
null,
null,
null,
{
"bSortable": false
}
],
"fnInitComplete": function (oSettings, json) {
$('#datatable-users_filter').append(" <button class='btn btn-sm btn-default' data-toggle='modal' data-target='#userAddModal'><span class='glyphicon glyphicon-user' aria-hidden='true'></span> Criar Novo</button>");
}
});
$('#datatable-questionnaires').dataTable({
"serverSide": true,
"ajax": {
"url": "handlers/_getQuestionnaires.asp?typeId=" + typeId
},
"aoColumns": [
null,
null,
null,
{
"bSortable": false
},
{
"bSortable": false
},
null
],
"fnDrawCallback": function () {
var $qActivate = $('.qActivate');
$qActivate.change(function () {
var isCheck = $(this).is(":checked");
var id = $(this).data('id');
jQuery.ajax({
data: {
id: id,
mode: isCheck
},
url: '../handlers/_activateQuestionnaire.asp',
type: 'POST'
});
});
},
"fnInitComplete": function (oSettings, json) {
$('#datatable-questionnaires_filter').append(" <a class='btn btn-sm btn-default' href='create_questionnaire.asp'><span class='glyphicon glyphicon-share-alt' aria-hidden='true'></span> Criar Novo</a>");
}
});
}
I'm trying to populate a table on a button click, getting the data from an ASP.NET ApiController. I've tried with almost all solutions posted in SO to other similar issues but always get that error.
Hope someone sees the problem.
The html markup:
<input type="button" ID="btnSearch" name="btnSearch" class="btn btn-success" value="Buscar" />
<table id="ResultsTable" class="table table-bordered table-condensed" style="font-size: 11px;">
<thead>
<tr>
<th><%=GetLiteral("Codigo")%></th>
<th><%=GetLiteral("Descripcion")%></th>
<th><%=GetLiteral("Marca")%></th>
<th><%=GetLiteral("IC")%></th>
<th><%=GetLiteral("IV")%></th>
<th><%=GetLiteral("Tarifa")%></th>
<th><%=GetLiteral("Precio")%></th>
<th><%=GetLiteral("P")%></th>
<th><%=GetLiteral("Total")%></th>
<th><%=GetLiteral("Central")%></th>
<th><%=GetLiteral("Centro")%></th>
</tr>
</thead>
<tbody>
</tbody>
The JS:
$(document).ready(function () {
var SearchTable = $("#ResultsTable").DataTable({
columns: [
{ data: "pCodigo" },
{ data: "rDescripcion" },
{ data: "rMarca" },
{ data: "xIndiceCarga" },
{ data: "xIndiceVelocidad" },
{ data: "TARIFA" },
{ data: "PRECIO" },
{ data: "PROVIENE" },
{ data: "TOTAL" },
{ data: "CENTRAL" },
{ data: "CENTRO" }
],
ordering: false,
searching: false
});
$("#btnSearch").click(function () {
var searchText = $("#<%=txtSearch.ClientID%>").val();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '<%=ResolveUrl("~/api/ProductSearch/")%>' + searchText + '/0138107',
dataType: "json"
}).success(function(result) {
SearchTable.clear().draw();
SearchTable.rows.add(result).draw();
}).fail(function(jqXHR, textStatus, errorThrown) {
alert("FAIL: " + textStatus + " = " + errorThrown);
});
});
}
A data sample:
[{
"RowError": "",
"RowState": 2,
"Table": [{
"pCodigo": "10006908",
"rDescripcion": "225/65/16-VAN100(112R)CO B-B-72-2",
"rMarca": "CONTI",
"xDibujo": 254176,
"xIndiceCarga": "112",
"xIndiceVelocidad": "R",
"xEje": 0,
"xAplicacion": 0,
"xDecimales": false,
"xTipoIVA": 2,
"xTasa": 2.550,
"TARIFA": 203.50,
"PRECIO": 105.54,
"PROVIENE": "LG",
"COLOR": 8454143,
"TOTAL": 3.00,
"CENTRAL": 2.00,
"CENTRO": 2.00,
"xControl": true
},
{
"pCodigo": "30000159",
"rDescripcion": "225/65/16-RF09(112R)ROTALLA E-C-73-3",
"rMarca": "ROTAL",
"xDibujo": 253405,
"xIndiceCarga": "112",
"xIndiceVelocidad": "R",
"xEje": 0,
"xAplicacion": 0,
"xDecimales": false,
"xTipoIVA": 2,
"xTasa": 2.550,
"TARIFA": 69.00,
"PRECIO": 49.29,
"PROVIENE": "LG",
"COLOR": 16777088,
"TOTAL": 89.00,
"CENTRAL": 55.00,
"CENTRO": 55.00,
"xControl": true
}],
"ItemArray": ["30000159",
"225/65/16-RF09(112R)ROTALLA E-C-73-3",
"ROTAL",
253405,
"112",
"R",
0,
0,
false,
2,
2.550,
69.00,
49.29,
"LG",
16777088,
89.00,
55.00,
55.00,
true],
"HasErrors": false
}]
Note: The GetLiteral function in html markup returns a string with the column name internationalized, that can be different from the text shown and column name. I think that's not the problem.
Thanks in advance!
You must insert the Table array :
}).success(function(result) {
SearchTable.clear().draw();
SearchTable.rows.add(result[0].Table).draw();
})
alternatively you can cycle through the Table array and add each item individually :
}).success(function(result) {
SearchTable.clear().draw();
for (var i=0;i<result.Table.length;i++) {
SearchTable.row.add(result[0].Table[i]).draw();
}
})