I've used DataTable to load data from SQL Server and display to Table.
But it just loads data.
Reference: https://gyazo.com/a77f5bee9c8f4fda3be8f9d130499bbf
Not only show this message:
No records found to show
but also, select page and page size selector don't display
Normal: https://gyazo.com/3f6d5193f36b756f752bdd20523d64e0
I hope you guys can give me a kind helpings. Thanks so much
HTML:
<table class="table table-striped table-bordered table-hover table-checkable" id="datatable_products">
<thead>
<tr role="row" class="heading">
<th width="1%">
<input type="checkbox" class="group-checkable">
</th>
<th width="10%"> ID </th>
<th width="15%"> Product Name </th>
<th width="15%"> Category </th>
<th width="10%"> Price </th>
<th width="15%"> Promotion Price </th>
<th width="10%"> Quantity </th>
<th width="15%"> Date Created </th>
<th width="10%"> Status </th>
<th width="10%"> Actions </th>
</tr>
</thead>
<tbody>
</tbody>
</table>
SQL Stored Procedure:
USE [OnlineShop]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[LoadProduct]
#Start INT=0,
#PageLimit INT=10
AS
BEGIN
SET NOCOUNT ON;
SELECT p.ID, p.Name, c.Name Category, p.Price, p.PromotionPrice, (SELECT SUM(Quantity) FROM ProductSizeColor WHERE ProductID = p.ID) as 'SumQuantity', p.CreatedDate, p.[Status]
FROM Product p
LEFT JOIN ProductCategory c
ON p.CategoryID = c.ID
ORDER BY ID
OFFSET #Start ROW
FETCH NEXT #PageLimit ROWS ONLY
END
Javascript:
var handleProducts = function() {
var grid = new Datatable();
grid.init({
src: $("#datatable_products"),
onSuccess: function(grid) {
// execute some code after table records loaded
},
onError: function(grid) {
// execute some code on network or other general error
},
loadingMessage: 'Loading...',
dataTable: {
"lengthMenu": [
[10, 20, 50, 100, 150],
[10, 20, 50, 100, 150] // change per page values here
],
"pageLength": 10, // default record count per page
"ajax": {
"url": "LoadProductTest", // ajax source
},
"processing": true,
"serverSide": true,
"columns": [
{"data": "ForCheckbox"},
{"data": "ID"},
{"data": "Name"},
{"data": "Category"},
{"data": "Price"},
{"data": "PromotionPrice"},
{"data": "SumQuantity"},
{"data": "CreatedDate"},
{"data": "DisplayStatus"},
{"data": "ForAction"},
],
"order": [
[1, "asc"]
] // set first column as a default sort by asc
}
});
Controller:
public ActionResult LoadProductTest()
{
//
var draw = Request.Form.GetValues("draw").FirstOrDefault();
var start = Request.Form.GetValues("start").FirstOrDefault();
var length = Request.Form.GetValues("length").FirstOrDefault();
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
var model = new ProductDao().LoadProduct(skip, pageSize);
int totalRecords = 0;
return Json(new { draw = draw, recordsFiltered = totalRecords, recordsTotal = totalRecords, data = model } , JsonRequestBehavior.AllowGet);
}
Method Load Product:
public List<ProductViewModel> LoadProduct(int start, int pageLimit)
{
object[] sqlParams = {
new SqlParameter("#Start", start),
new SqlParameter("#PageLimit", pageLimit)
};
return _db.Database.SqlQuery<ProductViewModel>("LoadProduct #Start, #PageLimit", sqlParams).ToList();
}
I found out how to resolve this problem.
In controller, I've set totalRecords = 0. It's wrong, it should get total records from table.
So, You no need to change any thing else but write new Stored Procedure to get count of record.
Controller : change totalRecords = 0 to
int totalRecords = new ProductDao().CountProduct();
CountProduct funtion:
public int CountProduct()
{
return _db.Database.SqlQuery<int>("CountProduct").SingleOrDefault();
}
Stored Procedure to count records:
CREATE PROCEDURE CountProduct
AS
BEGIN
SELECT COUNT(*) FROM Product
END
GO
Related
Currently I have a validation where I disable the buttons depending on the numerical value as follows:
disabled = [0,2,3,5]
/* Formatting function for row details - modify as you need */
function format(d) {
// `d` is the original data object for the row
$tipoproveedor = $("#txttipoproveedor").val();
console.log(d);
let tabla = `<table cellpadding="5" cellspacing="0" style="border-collapse: separate; border-spacing: 40px 5px;">
<thead>
<tr>
<th>
Date Order
</th>
<th>
Order
</th>
<th>
Status
</th>
</tr>
</thead>
<tbody>`;
d.Factura.forEach(f => { tabla +=
`<tr>
<td>${f.DateInvoice}</td>
<td>${f.Invoice}</td>
<td>${f.Status}</td>
<td><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#ModalCargaFactura" onclick="LoadInvoice('${f.PurchaseOrder}' )"`;
if($tipoproveedor != '0'){
if (disabled.indexOf(f.Estatus) > -1) {
tabla += ` disabled `;
}
}
tabla += `>Upload Documents</button></td>
<td><button type="button" class="btn btn-primary" onclick="ShowDetailsInvoice('${f.Invoice}')">Details</button></td>
</tr>`;
});
tabla += '</tbody></table>';
return tabla;
}
Where I disable the button in the values 0,2,3,5 now these values will change to strings giving the following assignment to the numeric values like this:
0 = 'None'
2 = 'Accept'
3 = 'Send'
5 = 'Delivered'
What I require now is to validate no longer with the numbers but with the character string, I hope someone can give me some guidance with this validation.
Update 1:
Based on the answer I have made the following code changing my array of values for strings as follows:
disabled = ['None','Accept','Send','Delivered']
/* Formatting function for row details - modify as you need */
function format(d) {
// `d` is the original data object for the row
$tipoproveedor = $("#txttipoproveedor").val();
console.log(d);
let tabla = `<table cellpadding="5" cellspacing="0" style="border-collapse: separate; border-spacing: 40px 5px;">
<thead>
<tr>
<th>
Date Order
</th>
<th>
Order
</th>
<th>
Status
</th>
</tr>
</thead>
<tbody>`;
d.Factura.forEach(f => {tabla +=
`<tr>
<td>${f.DateInvoice}</td>
<td>${f.Invoice}</td>
<td>${f.Status}</td>
<td><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#ModalCargaFactura" onclick="LoadInvoice('${f.PurchaseOrder}' )"`;
if($tipoproveedor != '0'){
if (disabled.indexOf(f.Estatus) > -1) {
tabla += ` disabled `;
}
}
tabla += `>Upload Documents</button></td>
<td><button type="button" class="btn btn-primary" onclick="ShowDetailsInvoice('${f.Invoice}')">Details</button></td>
</tr>`;
});
tabla += '</tbody></table>';
return tabla;
}
What little I understand is that the validation no longer detects the numerical values that existed in the array disabled and for this reason it marks the error and the data is not loaded into the table.
It will explain a little more in detail, currently I have in the table the column Status where the values are shown 0,2,3,5 and the buttons are disabled or enabled depending on their value. In this case I have been forced to change these same values for strings and in order not to complicate my life much I have decided to make this change from the query with which I show the data in the table with its simple caselike this:
CASE STATUS
WHEN 0 THEN 'None'
WHEN 1 THEN 'Receipment'
WHEN 2 THEN 'Accept'
WHEN 3 THEN 'Send'
WHEN 4 THEN 'Process'
WHEN 5 THEN 'Delivered'
ELSE 'Other'
END as 'STATUS'
Save the values as an object in the form:
const disabledValues = {
0: 'None',
2: 'Accept',
3: 'Send',
5: 'Delivered',
};
Later, during a comparison, cast your Estatus into the number (adding + at the beginning) and use it in the form:
if (disabledValues[+f.Estatus]) {
tabla += ` disabled `;
}
Maybe I'm misunderstanding the question, but it sounds like you now expect .Estatus to contain a string instead of a number, and you still want the button disabling to work? If that's the case just change
disabled = [0,2,3,5]
to
disabled = ['None', 'Accept', 'Send', 'Delivered']
or even
disabled = [0, 2, 3, 5, 'None', 'Accept', 'Send', 'Delivered']
so you can handle both.
disabled = [0, 2, 3, 5, 'None', 'Accept', 'Send', 'Delivered']
/* Formatting function for row details - modify as you need */
function format(d) {
// `d` is the original data object for the row
$tipoproveedor = $("#txttipoproveedor").val();
console.log(d);
let tabla = `<table cellpadding="5" cellspacing="0" style="border-collapse: separate; border-spacing: 40px 5px;">
<thead>
<tr>
<th>
Date Order
</th>
<th>
Order
</th>
<th>
Status
</th>
</tr>
</thead>
<tbody>`;
d.Factura.forEach(f => {
tabla += `<tr>
<td>${f.DateInvoice}</td>
<td>${f.Invoice}</td>
<td>${f.Status}</td>
<td><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#ModalCargaFactura" onclick="LoadInvoice('${f.PurchaseOrder}' )"`;
if($tipoproveedor != '0'){
if (disabled.indexOf(f.Estatus) > -1) {
tabla += ` disabled `;
}
}
tabla += `>Upload Documents</button></td>
<td><button type="button" class="btn btn-primary" onclick="ShowDetailsInvoice('${f.Invoice}')">Details</button></td>
</tr>`;
});
tabla += '</tbody></table>';
return tabla;
}
Initialise you array like below, where you can customize your message.
const valuesToDisable = [
{
value: 0,
note: 'None'
},
{
value: 2,
note: 'Accept'
},
{
value: 3,
note: 'Send'
},
{
value: 5,
note: 'Delivered'
}
]
Iterate through the array and display it's note accordingly.
First, define your statuses in an object, give them a value how a button is disabled:
const statuses = {
None: true,
Receipment: false,
Accept: true,
Send: true,
Process: true,
Delivered: true,
Other: false,
};
Then tune your code as:
if ($tipoproveedor != '0') {
if (statuses[f.Estatus]) {
tabla += ` disabled `;
}
}
Just a quick idea, can be optimised further:
Your array :
const disabled = [
{
id: 0,
text: 'None'
},
{
id: 2,
text: 'Accept'
},
{
id: 3,
text: 'Send'
},
{
id: 5,
text: 'Delivered'
}
];
A function to determinate the status
isButtonDisabled = function(status) {
const found = disabled.filter(d => {
return d.text === status;
});
return found.length ? true : false
}
Usage:
if ($tipoproveedor != '0'){
if (isButtonDisabled(f.Estatus)) {
tabla += ` disabled `;
}
}
After reading the question and all the answers I failed to understand why it's not working.
By saying "I have been forced to change these same values for strings" if the questioner means,
now the array disabled = [ "0", "2", "3", "5" ]
and typeof f.Estatus === "string" then the solution is obvious.
const disabled = [ "0", "2", "3", "5" ]
if(disabled.includes(f.Estatus))
tabla += "disabled"
I am trying to retrieve data from database and display it into Data Table but this error is keep appearing:
DataTables warning: table id=userTable - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
When I tried to check its response in Developer tools (I use Chromium Edge) it does not have any data and contains only message:
This request has no response data available
I have this in my web.php:
Route::get('user/datatable', 'UserController#datatable')->name('user/datatable')->middleware('role:admin');
My snippet code from controller file (UserController):
public function datatable()
{
$data = User::where('status', '=', 1)->get();
return DataTables::of($data)
->addColumn('action', function($data){
$url_edit = url('user/'.$data->id.'/edit');
$url = url('user/'.$data->id);
$view = "<a class = 'btn btn-primary' href = '".$url."' title = 'View'><i class = 'nav icon fas fa-eye'></i></a>";
$edit = "<a class = 'btn btn-warning' href = '".$url_edit."' title = 'Edit'><i class = 'nav icon fas fa-edit'></i></a>";
$delete = "<button data-url = '".$url."' onclick = 'deleteData(this)' class = 'btn btn-action btn-danger' title = 'Delete'><i class = 'nav-icon fas fa-trash-alt'></i></button>";
return $view."".$edit."".$delete;
})
->rawColumns(['action'])
->editColumn('id', 'ID:{{$user_id}}')
->make(true);
}
My snippet code from the index blade file (jscript part at the bottom of blade file):
#push('js')
<script>
$(document).ready(function () {
var table1 = $("#userTable").DataTable({
responsive:true,
processing:true,
pagingType: 'full_numbers',
stateSave:false,
scrollY:true,
scrollX:true,
autoWidth: false,
ajax:"{{url('user/datatable')}}",
order:[0, 'desc'],
columns:[
{data:'first_name', name: 'First Name'},
{data:'last_name', name: 'First Name'},
{data:'email', name: 'E-Mail Address'},
{data:'action', name: 'Action', searchable: true, sortable:true},
]
});
...
</script>
#endpush
And finally where the data will be displayed (index blade file):
<table id="userTable" class="table table-bordered table-striped" data-toggle = "table1_" style = "width: 100%;">
<thead>
<tr>
<th class="all">First Name</th>
<th class="all">Last Name</th>
<th class="all">E-Mail Address</th>
<th class="all">Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>E-Mail Address</th>
<th>Action</th>
</tr>
</tfoot>
</table>
I don't know what's wrong or where's the part that causes an error or problem because it doesn't show any response or data.
When i try to display the contents of this line by using dd():
$data = User::where('status', '=', 1);
It does not show any data from database but when I try this code that does the same it retrieves data from the database but still the DataTable error is appearing:
$data = DB::table('users')
->select('*')
->where('status', '=', 1)
->orderBy('id', 'desc')
->get();
I don't exactly know whether the data retrieval or data displaying
implementation or both is the problem.
What is the cause/s of the error/s or problem/s that results?
I'm trying to implement Server Side DataTable.
Everything goes perfectly fine up to the last rowCallback where I'm appending button to additional column for Actions (i.e. Edit/Delete).
Issue:
Here's my code.
<link href="~/Content/datatables.min.css" rel="stylesheet" /> //<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.16/datatables.min.css"/>
<link href="~/Content/font-awesome.min.css" rel="stylesheet" />
<div class="container">
<div class="row" style="margin-top:25px">
<table class="table table-bordered table-responsive dataTables-list">
<thead>
<tr>
<th>
Id
</th>
<th>
Name
</th>
<th>
Actions
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<i class="fa fa-pencil"></i>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
JavaScript:
<script src="~/Scripts/datatables.min.js"></script> //<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.10.16/datatables.min.js"></script>
<script>
$(document).ready(function () {
$('.dataTables-list').DataTable({
/*Sorting*/
"bSort": true,
"aoColumnDefs": [{
'bSortable': true
}],
"processing": true, // for show progress bar
"serverSide": true, // for process server side
"ajax": {
"url": "/Home/LoadData",
"type": "POST",
"datatype": "json"
},
"aoColumns": [{
"mDataProp": "Id"
}, {
"mDataProp": "Name"
}, {
"mDataProp": "Actions"
}],
"rowCallback": function (row, data, index) {
var newBtns = '<i class="fa fa-pencil"></i> ';
// $(row).append(newBtns);
$('td:eq(2)', row).html(newBtns);
},
language: {
paginate: {
next: '»',
previous: '«'
},
emptyTable: "Der er ingen poster.",
sInfo: "Viser _START_ til _END_ af poster."
}
});
});
</script>
Controller:
[HttpPost]
public ActionResult LoadData()
{
try
{
var draw = Request.Form.GetValues("draw").FirstOrDefault();
var start = Request.Form.GetValues("start").FirstOrDefault();
var length = Request.Form.GetValues("length").FirstOrDefault();
//Find Order Column
var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][data]").FirstOrDefault();
var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordsTotal = 0;
var v = (from a in _db.AllRoles select a); //Table contains only two Columns - Id and Name
//SORT
if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
{
v = v.OrderBy(sortColumn + " " + sortColumnDir);
}
recordsTotal = v.Count();
var data = v.Skip(skip).Take(pageSize).ToList();
return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
throw;
}
}
The issue is due to column difference may be but I don't know how to solve it as implementing ServerSide Datatable for first time.
Thanks in advance.
I modified the below section in my Code to solve the Error.
"aoColumns": [{
"mDataProp": "Id"
}, {
"mDataProp": "Name"
}, {
"mDataProp": "Actions",
"defaultContent": '<i class="fa fa-pencil"></i> '
}],
I added defaultContent for that column as it is not getting values from Database/Sp.
P.S. Answer provided by #dee is also correct and will solve the error. Both are the Solutions to this Question.
The link in the error message provides very good information about what is the problem. You have specified three columns for the DataTable function but as you write in the comment Table contains only two Columns - Id and Name.
"aoColumns": [{
"mDataProp": "Id"
}, {
"mDataProp": "Name"
}, {
"mDataProp": "Actions"
}],
The Resolution section of the document tells what is needed to do:
If using columns ensure that you have specified exactly the number of columns that are present in the HTML for the table.
So you will need the transform the result of the query into another class which will have additional property for Actions. HTH
I have an error in my code and can’t figure out, what i did wrong.
The datatable gets filled correctly and on ajax.refresh the table gets valid json-data, but the table does not reload.
HTML
<table id="monatsabschluss" class="listing">
<thead class="header">
<tr>
<th>Aufgabe</th>
<th>Status<input type="checkbox" id ="express" ></th>
</tr>
</thead>
<tbody>
Javascript
var adat = '20160606';
var kid = 7;
var table = $('#monatsabschluss').DataTable( {
"paging": false,
"info": false,
"filter": false,
"ordering": false,
"processing": true,
"serverSide": true,
"ajax": {
"url": "/management/bavabrech/fetchjobs",
"data": function ( d ) {
d.kid = kid;
d.adat = adat;
},
"dataSrc": "data",
},
"columns": [
{ "data": "description" },
{ "data": "status", className: 'statusCol' },
],
});
setInterval( function () {
table.ajax.reload( null, false );
}, 5000 );
Json
{"sEcho":1,
"success":true,
"iTotalRecords":0,
"iTotalDisplayRecords":0,
"aaData":
[{"description":"Erstellen Rentendaten",
"status":3,"id":"1"},
{"description":"Pr\u00fcfliste erstellen",
"status":4,"id":"2"},
{"description":"TEXT","status":"","id":"out_2"}]}
HTML-Output from the initial Datatable-loading
<table class="listing dataTable no-footer" id="monatsabschluss"
role="grid" style="width: 800px;">
<thead class="header">
<tr role="row">
<th class="sorting_disabled" rowspan="1" colspan="1"
style="width: 469px;">Aufgabe</th>
<th class="sorting_disabled statusCol" rowspan="1" colspan="1"
style="width: 269px;">Status<input type="checkbox" id="express">
</th>
</tr>
</thead>
<tbody class="">
<tr role="row" class="maStatusRunning">
<td>Erstellen Rentendaten</td>
<td class=" statusCol">Wird ausgeführt</td>
</tr>
<tr role="row" class="maStatusComplete">
<td>Prüfliste erstellen</td>
<td class=" statusCol">Erledigt</td>
</tr>
<tr role="row" class="odd">
<td>TEXT</td>
<td class=" statusCol"></td>
</tr>
</tbody>
</table>
I am using Datatable 1.10.7, i do not get any error messages.
Ok, I have installed all your code and dug deeper into the problem. Your issue is with your serverSide property. When that is on true, the client expects you to mirror the draw property send to the server so he know that the response he got is for the request he sent (see https://datatables.net/manual/server-side). I also saw that you are using deprecated property names in your response (aaData etc....). You have to change those, so he recognizes your draw property.
That is how the response looks on my side and how it works in my example with your code
<?php
header('Content-type: application/json');
?>
{
"success":true,
"recordsTotal":0,
"recordsFiltered":0,
"draw": <?= (int)$_GET['draw'] ?>,
"data":
[
{"description":"Erstellen Rentendaten", "status":3,"id":"1"},
{"description":"Pr\u00fcfliste erstellen", "status":4,"id":"2"},
{"description":"TEXT","status":"","id":"out_2"}
]
}
I have added mirroring the draw property (you can see that in the request url) and renamed aaData to data, iTotalRecords to recordsTotal, iTotalDisplayRecords to recordsFiltered and removed iEcho
I haven't tried your example yet, but I can tell a few javascript errors you have.
First of all your data function definition is wrong
"data": function ( d ) {
d.kid = kid,
d.adat = adat
},
The function body is no valid Javascript.
Then there are trailing commas that not every browser likes and that are invalid for json
"dataSrc": "data",
{ "data": "status", className: 'statusCol' },
and at the end of your table defintion after the columns part. Do you use an IDE? It should highlight those occurences.
I would start putting a debugger call into your data method so you can track down what happens in there.
There are few problems with your code. The most important thing to remember: always have defined all columns that come with AJAX, hide them via API.
Second thing, do not mix datatables 1.X and 2.X code. It appears to me, that your column definition is for version 2.X, wheras rest of the code is version 1.X
So:
Your columns definition is wrong. You're missing one column
"aaData": [
{ ""mData"": "description" },
{ ""mData"": "status"},
{ "sClass": "statusCol" }
],
If you would like to hide column, use bVisible parameter
{ "sName":"id", "sTitle":"Foo", "sClass":"center", "sWidth":"10%", "bSortable":"false", "bVisible": false },
I would also change the table html markup to
thead
<tr>
<th>ID</th>
<th>Aufgabe</th>
<th>Status<input type="checkbox" id="express"></th>
</tr>
tbody
<tr>
<td colspan="3">No data yet</td>
</tr>
It's always good practive, to use iniutComplete, to see if everything was ok:
"fnInitComplete": function (){
console.log("Init done");
},
And the last thing: if you have would like to have extra content inside TD cells, use cell custom renderer.
{
"mRender" : function(data, type, row){
var sb = [];
sb.push('<div class="test' + data + '" title="' + row[2] + '"> </div>');
return sb.join();
}
},
I am using server side processing to read the database table and convert the records into Json file, and pass it to the database table to display data.
Read database and convert it into json:
code:
Route::get('banner/list/banners/json/{id}', function ()
{
$banner = DB::table('banner_creatives')->where('Id','=','53')->get();
$recordsTotal = count($banner);
$data['draw'] = 1;
$data['recordsTotal'] = $recordsTotal;
$data['recordsFiltered'] = $recordsTotal;
$data['data'] = $banner;
return Response::json($data);
});
Json output:
{"draw":1,"recordsTotal":1,"recordsFiltered":1,"data":[{"id":1,"bId":26,"cId":53,"bName":"32_32_53.jpeg","storageType":"url","width":32,"height":32,"weight":1,"imageURL":"localhost:8000\\\/banner\\\/view\\\/32_32_53.jpeg","clickURL":"","created_at":"2015-01-26 12:32:28","updated_at":"2015-01-26 12:32:28","deleted_at":null}]}
As you can see on this json, I have the image Url that I want to display it on the table.
JavaScript code:
$(document).ready(function() {
var table = $('#banner').DataTable( {
"processing": true,
"serverSide": false,
"ajax": "banners/json/53",
"columns": [
{ "data": "id" },
{ "data": "bannerId" },
{ "data": "campaignId" },
{ "data": "bannerName" },
{ "data": "width" },
{ "data": "height" },
{ "data": "imageUrl" }
});
});
Datatable code:
<table id="banner" class="display table table-striped table-bordered table-hover dataTable no-footer" cellspacing="0" width="100%">
<thead>
<tr>
<th>id</th>
<th>Banner Id</th>
<th>Campaign Id</th>
<th>Banner Name</th>
<th>Width</th>
<th>Height</th>
<th>Image/Banner</th>
</tr>
</thead>
<tfoot>
<tr>
<th>id</th>
<th>Banner Id</th>
<th>Campaign Id</th>
<th>Banner Name</th>
<th>Width</th>
<th>Height</th>
<th>Image/Banner</th>
</tr>
</tfoot>
</table>
On the last column it displaying the image URL but is not what i want, i want to display the usually image on the datatable using the URL, if it possible.
You can use the columns.render option to specify a callback function that can modify the data that is rendered in the column.
The callback function takes three parameters (four since 1.10.1). The first parameter is the original data for the cell (the data from the db), the second parameter is the call type (filter, display, type, or sort), and the third parameter is the full data source for the row. The function should return the string that should be rendered in the cell.
In your columns definition, add the render option to your imageUrl column definition:
{
"data": "imageUrl",
"render": function(data, type, row) {
return '<img src="'+data+'" />';
}
}
Documentation on the render option found here.
Here's my solution, hope it helps someone.
{
'targets': [15,16],
'searchable': false,
'orderable':false,
'render': function (data, type, full, meta) {
return '<img src="'+data+'" style="height:100px;width:100px;"/>';
}
},
"columnDefs": [
{
// The `data` parameter refers to the data for the cell (defined by the
// `data` option, which defaults to the column being worked with, in
// this case `data: 0`.
"render": function ( data, type, row ) {
return '<img src="'+data+'" style="width=300px;height=300px;" />';
},
"targets": 1 // column index
}
]