How can I show Base64 image in a server-side DataTable? - javascript

This is my HTML for server side data to load the data into the table of the data get data from controller
<script type="text/template" id="tablescript">
<td><%=Name%></td>
<td><%=PhoneNumber%></td>
<td><%=CNIC%></td>
<td><%=So%></td>
<td><%=Thumb%></td>
<td><%=Image%></td>
<td><%=NomineeImage%></td>
<td>
<i class="fa fa-pencil-square-o" aria-hidden="true" onclick="editMember('<%= Id%>')" style="cursor:pointer;font-size: 20px;"></i>
<span class="fa fa-trash" aria-hidden="true" style="cursor:pointer;color:red;font-size: 20px;" onclick="deleteMember('<%= Id%>')"></span>
<span class="fa fa-ban" aria-hidden="true" style="cursor:pointer;color:red;font-size: 20px;" onclick="blockMember('<%= Id%>')"></span>
<span class="fa fa-check" aria-hidden="true" style="cursor:pointer;color:green;font-size: 20px;" onclick="activeMember('<%= Id%>')"></span>
</td>
</script>
<table class="table table-hover table-bordered table-striped" id="tblloaddata"></table>
Ajax Request go to the mvc controller and get the list was load to model but not show my datatable.
var table;
var loadtable = function () {
var getUrl = $("#hidLoadMembersUrl").val();
var tmpl = _.template($("#tablescript").html());
table = $("#tblloaddata").DataTable({
"processing": true,
"serverSide": true,
"ajax": {
url: getUrl,
type: "POST"
},
"columns": [
{ "data": "Name", "title": "Name" },
{ "data": "PhoneNumber", "title": "PhoneNumber" },
{ "data": "CNIC", "title": "CNIC" },
{ "data": "So", "title": "SoDoWoName" },
{ "data": "Thumb", "title": "Thumb" },
{ "data": "Image", "title": "Image" },
{ "data": "NomineeImage", "title": "NomineeImage" },
{ "data": null, "title": "Action", "orderable": "false" },
],
"rowCallback": function (row, data) {
console.log(data);
$(row).html(tmpl(data));
}
});
};

You should use render property to display images;
table = $("#tblloaddata").DataTable({
"processing": true,
"serverSide": true,
"ajax": {
url: getUrl,
type: "POST"
},
"columns": [
{ "data": "Name", "title": "Name" },
{ "data": "PhoneNumber", "title": "PhoneNumber" },
{ "data": "CNIC", "title": "CNIC" },
{ "data": "So", "title": "SoDoWoName" },
{ "data": "Thumb", "title": "Thumb" },
{ "data": "Image", "title": "Image", render : function (data, type, full, meta)
{ return '<img src="'+data.Image+'"/>'; }
},
{ "data": "NomineeImage", "title": "NomineeImage" },
{ "data": null, "title": "Action", "orderable": "false" },
],
"rowCallback": function (row, data) {
console.log(data);
$(row).html(tmpl(data));
}
});

Related

How can I select children options from optgroup in Select2?

Question:
I have successfully created a select2 template with a group but I can't select the items in it, is there anything missing from the code I made below? Any help from you means a lot to me, thank you
See this first,
Preview Image
For the data below, i folow https://select2.org/data-sources/formats
Result from AJAX :
{
"status": true,
"message": null,
"data": [
{
"text": "Bank",
"children": [
{
"id": "002",
"icon": ".../payment/bri_1.png",
"text": "BANK BRI"
},
{
"id": "008",
"icon": ".../payment/mandiri_1.png",
"text": "BANK MANDIRI"
},
{
"id": "009",
"icon": ".../payment/bni_1.png",
"text": "BANK BNI / SYARIAH"
},
{
"id": "014",
"icon": ".../payment/bca_1.png",
"text": "BANK BCA"
},
{
"id": "022",
"icon": ".../payment/1280px-CIMB_Niaga_logo.svg.png",
"text": "CIMB NIAGA / SYARIAH"
},
{
"id": "016",
"icon": ".../payment/Maybank-Logo.png",
"text": "Maybank"
},
{
"id": "013",
"icon": ".../payment/images.png",
"text": "PERMATA BANK"
},
{
"id": "213",
"icon": ".../payment/Jenius-logo.png",
"text": "Jenius/BTPN"
},
{
"id": "011",
"icon": ".../payment/kissclipart-danamon-logo-png-clipart-bank-danamon-logo-a9b2b21755c37a3a.png",
"text": "Danamon"
},
{
"id": "012",
"icon": ".../payment/images_1.png",
"text": "Bank Neo Commerce/Bank Yudha Bakti"
},
{
"id": "017",
"icon": ".../payment/images-removebg-preview.png",
"text": "Bank Syariah Indonesia"
}
]
},
{
"text": "eMoney",
"children": [
{
"id": "900",
"icon": ".../payment/ovo.png",
"text": "OVO"
},
{
"id": "901",
"icon": ".../payment/gopay.png",
"text": "GOPAY"
},
{
"id": "903",
"icon": ".../payment/dana_1.png",
"text": "DANA"
},
{
"id": "904",
"icon": ".../payment/linkaja.png",
"text": "LINK AJA"
},
{
"id": "906",
"icon": ".../payment/shopeepay-shopee.co.id_ratio-16x9.jpg",
"text": "SHOPEE PAY"
}
]
}
]
}
Code :
$("#payment").select2({
placeholder: 'Payment',
width: 'resolve',
minimumResultsForSearch: Infinity,
templateResult: function formatState(state) {
if (!state.id) return state.text;
var $state = $(
'<span><img src="' + state.icon + '" style="width:30px;"/> ' + state.text + '</span>'
);
return $state;
},
ajax: {
url: base_url + 'user/api/payment',
dataType: 'json',
processResults: function(data) {
return {
results: $.map(data.data, function(item, key) {
var children = [];
for (var k in item.children) {
var childItem = [];
childItem.id = item.children[k].id;
childItem.icon = item.children[k].icon;
childItem.text = item.children[k].text;
children.push(childItem);
}
return {
text: item.text,
children: children,
}
})
};
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Payment</label>
<div class="col-sm-10">
<select name="payment" id="payment" class="form-control">
</select>
</div>
</div>
As far as I can see in your code, your API is returning results already formatted, so keep it simple. Please check this fiddle with a fully working example based on your code.
$("#payment").select2({
placeholder: 'Payment',
width: 'resolve',
ajax: {
url: 'https://randomuser.me/api/', //a random URL to simulate a request response in jsfiddle
dataType: 'json',
processResults: (data) => ({ results: response.data })
}
});

How to pass request body data in type POST using Datatable for Serverside pagination using Javascript

I am trying to implement ServerSide pagination using Datatable for AJAX POST request
here is my Javascript Code, if I use JSON.stringify for data field then api won't hit
$('#tripboard_table').DataTable({
proccessing: true,
serverSide: true,
ajax: {
"url": "http://localhost:5000/api/v1/trip/get-trip-list",
"contentType": "application/json; charset=utf-8",
"type": "POST",
"dataType": "json",
"data": {
"driver_id": "",
"franchise_id": login_data.franchise_id,
"page_no": 0,
"page_size": 10
}
},
columns: [
{ "data": "" },
{ "data": "reference_number" },
{ "data": "consignor_name" },
{ "data": "consignee_name" },
{ "data": "from_city" },
{ "data": "to_city" },
{ "data": "status" },
{ "data": "route_name" },
{ "data": "vehicle_number" },
{ "data": "driver_name" },
{ "data": "pickup_date" },
{ "data": "scheduled_delivery_date" },
{ "data": "total_money_allocated" },
{ "data": "total_money_released" }
]
});
if we remove JSON.stringify function from data and passed data as it is then api gets hit and showing error alert that
DataTables warning: table id=tripboard_table - Ajax error. For more
information about this error, please see http://datatables.net/tn/7
and no data is inserted in table.
In console it shows
Method Not Allowed
The method is not allowed for the requested URL.
Please suggest solution for this..
Use this for adding to existing request of data table
function (d) {
d.driver_id = "";
d.franchise_id = login_data.franchise_id;
d.page_no = 0;
d.page_size = 10;
return d;
}
https://datatables.net/manual/server-side#Sent-parameters
$('#tripboard_table').DataTable({
proccessing: true,
serverSide: true,
ajax: {
"url": "http://localhost:5000/api/v1/trip/get-trip-list",
"contentType": "application/json; charset=utf-8",
"type": "POST",
"dataType": "json",
"data": function (d) {
d.driver_id = "";
d.franchise_id = login_data.franchise_id;
d.page_no = 0;
d.page_size = 10;
return JSON.stringify(d)
});
}
},
columns: [
{ "data": "" },
{ "data": "reference_number" },
{ "data": "consignor_name" },
{ "data": "consignee_name" },
{ "data": "from_city" },
{ "data": "to_city" },
{ "data": "status" },
{ "data": "route_name" },
{ "data": "vehicle_number" },
{ "data": "driver_name" },
{ "data": "pickup_date" },
{ "data": "scheduled_delivery_date" },
{ "data": "total_money_allocated" },
{ "data": "total_money_released" }
]
});

How to conditionally draw DataTables columns in Razor pages

Currently we are doing this to draw the columns for a server side DataTable for 2 different users, we were able to hide the column headers using razor code to only draw them when the user is an admin or group admin. However when it comes to drawing the data we are having an issue with the following:
function getTableColumns() {
var allowedToDelete = #(User.IsInRole("SysAdmin") || GroupManager.IsUserGroupAdmin(Model.GroupId, User.FindFirst(ClaimTypes.NameIdentifier).Value) ? "true" : "false");
if (allowedToDelete) {
return [{ "defaultContent": "" },
{ "data": "deadlineDate", "name": "DeadlineDate" },
{ "data": "priority", "name": "Priority" },
{ "data": "jobNumber", "name": "JobNumber" },
{ "data": "project", "name": "Project" },
{ "data": "description", "name": "Description" },
{ "data": "reference", "name": "Reference" },
{ "data": "subReference", "name": "SubReference" },
{ "data": "employee", "name": "Employee" },
{ "data": "allocatedTo", "name": "AllocatedTo" },
{
"render": function (data, type, full, meta) {
return "<i title ='Archive Item' class='fa fa-archive table-icon-view' onclick='archiveJob(\""
+ full.groupId + "\",\"" + full.id + "\")'></i>";
}
},
{
"render": function (data, type, full, meta) {
return "<i title ='Edit' class='fa fa-pencil table-icon-edit' onclick='editJob(\""
+ full.groupId + "\",\"" + full.id + "\")'></i>";
}
},
{
"render": function (data, type, full, meta) {
return "<i title ='Delete' class='fa fa-trash table-icon-delete' onclick='showDeleteModal(\""
+ full.groupId + "\",\"" + full.id + "\")'></i>";
}
},
{ "data": "issueDate" },
{ "data": "startDate" },
{ "data": "createdBy" },
{ "data": "createdDate" },
{ "data": "notes" }];
} else {
return [{ "defaultContent": "" },
{ "data": "deadlineDate", "name": "DeadlineDate" },
{ "data": "priority", "name": "Priority" },
{ "data": "jobNumber", "name": "JobNumber" },
{ "data": "project", "name": "Project" },
{ "data": "description", "name": "Description" },
{ "data": "reference", "name": "Reference" },
{ "data": "subReference", "name": "SubReference" },
{ "data": "employee", "name": "Employee" },
{ "data": "allocatedTo", "name": "AllocatedTo" },
{
"render": function (data, type, full, meta) {
return "<i title ='Edit' class='fa fa-pencil table-icon-edit' onclick='editJob(\""
+ full.groupId + "\",\"" + full.id + "\")'></i>";
}
},
{ "data": "issueDate" },
{ "data": "startDate" },
{ "data": "createdBy" },
{ "data": "createdDate" },
{ "data": "notes" }];
}
}
Is there a way to optimise this so that we don't have to repeat the code just to hide 2 icon links?
You could use the columns.visible option to display/hide the column accordingly.
Additionally, it might be worth looking at Reusable renderers to avoid some of the repetition with the rendering functions.
Creating such a rendering function may look like this:
$.fn.dataTable.render.icon = function ( title, icon, func) {
return function ( data, type, row ) {
return "<i title ='" + title + "' class='fa " + icon + "' onclick='" + func + "(\""
+ row.groupId + "\",\"" + row.id + "\")'></i>";
}
};
You could then use this as follows:
{
//Column visibility
visible: allowedToDelete,
//Reusable renderer
render: $.fn.dataTable.render.icon('Archive Item', 'fa-archive table-icon-view', 'archiveJob')
},
{
visible: allowedToDelete,
render: $.fn.dataTable.render.icon('Edit', 'fa-pencil table-icon-edit', 'editJob')
},
{
visible: allowedToDelete,
render: $.fn.dataTable.render.icon('Delete', 'fa-trash table-icon-delete', 'showDeleteModal')
},
You could have the default array be defined in a variable, and push the 2 icon links into it inside the if, before returning:
function getTableColumns() {
var allowedToDelete = #(User.IsInRole("SysAdmin") || GroupManager.IsUserGroupAdmin(Model.GroupId, User.FindFirst(ClaimTypes.NameIdentifier).Value) ? "true" : "false");
var dataArray = [{ "defaultContent": "" },
{ "data": "deadlineDate", "name": "DeadlineDate" },
{ "data": "priority", "name": "Priority" },
{ "data": "jobNumber", "name": "JobNumber" },
{ "data": "project", "name": "Project" },
{ "data": "description", "name": "Description" },
{ "data": "reference", "name": "Reference" },
{ "data": "subReference", "name": "SubReference" },
{ "data": "employee", "name": "Employee" },
{ "data": "allocatedTo", "name": "AllocatedTo" },
{
"render": function (data, type, full, meta) {
return "<i title ='Edit' class='fa fa-pencil table-icon-edit' onclick='editJob(\""
+ full.groupId + "\",\"" + full.id + "\")'></i>";
}
},
{ "data": "issueDate" },
{ "data": "startDate" },
{ "data": "createdBy" },
{ "data": "createdDate" },
{ "data": "notes" }];
if (allowedToDelete) {
return dataArray.Concat([{
"render": function (data, type, full, meta) {
return "<i title ='Edit' class='fa fa-pencil table-icon-edit' onclick='editJob(\""
+ full.groupId + "\",\"" + full.id + "\")'></i>";
}
},
{
"render": function (data, type, full, meta) {
return "<i title ='Delete' class='fa fa-trash table-icon-delete' onclick='showDeleteModal(\""
+ full.groupId + "\",\"" + full.id + "\")'></i>";
}
}]).ToArray();
} else {
return dataArray;
}
}

Two targets for the same column datatable

I have a datatable with json ajax.
But, i need to pass for the same column two targets. How i do that?
"columns": [
{ "data": "tpPedido" },
{ "data": "os" },
{ "data": "userMobile.nome" },
{ "data": "produto.nmProduto" },
{ "data": "status.NmStatus" },
{ "data": "produto.garantia.descricao" },
{ "data": "valor" },
{ "data": "valoradiantado" },
{ "data": "idPedidoAssistencia" },
{ "data": "idPedidoAssistencia" }
],
And the columndefs i trying to do this:
{ "render": function ( data, type, row ) {
return '<a onclick="relatorioAcerto('+data+')">R$: ' + parseFloat(data).toFixed(2).replace('.', ',').replace(/(\d)(?=(\d{3})+\,)/g, "$1." + '</a>');
}, "targets": 6,9},
You can define directly in columns array. render function accept three parameters. The last parameter holds entire data object.
"columns": [
{ "data": "tpPedido" },
{ "data": "os" },
{ "data": "userMobile.nome" },
{ "data": "produto.nmProduto" },
{ "data": "status.NmStatus" },
{ "data": "produto.garantia.descricao" },
{
"data": null,
"render" : function (data, type, row) {
return '<a href="'+row.idPedidoAssistencia+'" >Click here</a>';
}
},
{ "data": "valoradiantado" },
{ "data": "idPedidoAssistencia" },
{
"data": null,
"render" : function (data, type, row) {
return '<a href="'+row.idPedidoAssistencia+'" >Click here</a>';
}
}
],

Child items in kendo grid

How can i bind my child data in one column?
I want to write "Technology,Economy,Life" in same column and same row. But i think i need to loop in "Category". How can i do this, any idea?
My Data:
{
"ParentId": "00000000-0000-0000-0000-000000000000",
"Title": null,
"UserGroupModel": null,
"EntityAccessData": [
{
"EntityTitle": "User",
"Access": {
"Id": "59d0c6f7-8f93-497a-854d-bdd4a42ade94",
"Title": "Can Delete"
},
"Category": [
{
"Id": "00000000-0000-0000-0000-000000000000",
"Title": "Technology"
},
{
"Id": "00000000-0000-0000-0000-000000000000",
"Title": "Economy"
},
{
"Id": "00000000-0000-0000-0000-000000000000",
"Title": "Life"
}
],
"HasAccess": true
},
{
"EntityTitle": "UserGroup",
"Access": {
"Id": "7c65be44-11b0-4cf4-9104-0ad999e7e280",
"Title": "Can Edit"
},
"Category": [
{
"Id": "00000000-0000-0000-0000-000000000000",
"Title": "Technology"
},
{
"Id": "00000000-0000-0000-0000-000000000000",
"Title": "Economy"
},
{
"Id": "00000000-0000-0000-0000-000000000000",
"Title": "Life"
}
],
"HasAccess": true
}
]
}
My Script:
$("#grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: "/getData" },
schema: {
data: "EntityAccessData"
},
group: [{
field: "EntityTitle"
}],
},
columns: [
{
field: "Access.Id",
title: "ID"
},
{
field: "Access.Title",
title: "Access title"
},
{
field: "HasAccess",
title: "has access"
},
{
field: "Category.Title", // ***wrong***
title: "Category"
},
]
});
Define the schema as follow:
schema: {
data : "EntityAccessData",
model: {
CategoryTitle: function () {
var category = [];
$.each(this.Category, function(idx, elem) {
category.push(elem.Title);
});
return category.join(",");
}
}
},
Where I add an additional field CategoryTitle that is the result of joining the Title of the Category array and then define the column as:
{
field: "CategoryTitle()",
title: "Category"
}

Categories

Resources