How to call Function in Jquery Datatable - javascript

I have these lines of code. I want to add function to some row. When clicked it runs another function. But It not recognise function declaration.How can I call function when clicked some row? and how can i send parameters to that function associated with that row.
$(document).ready(function() {
var restVul = function() {
alert("tik");
}
$.ajax({
url: "https://localhost:450/rest/products?pageNumber=1&pageCount=80",
type: "POST",
dataType: "json",
headers: {
'Content-Type': 'application/json'
},
traditional: true,
contentType: "application/json; charset=utf-8",
processData: false,
data: JSON.stringify(hostAddresses),
success: function(response) {
console.log(response);
for (var i = 0; i < response.length; i++) {
var trHTML = '';
for (var j = 0; j < response[i].Products.length; j++) {
trHTML += '<tr class="clickable-row" data-href="index.html"><td>' + response[i].IP + '</td><td onclick="function () {alert(); }">' + response[i].Products[j].Product + '</td><td>' + response[i].Products[j].CVECount + '</td></tr>';
}
$('#ProductsTableBody').append(trHTML);
}
$('.js-exportable').DataTable({
dom: 'Bfrtip',
responsive: true,
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
]
});
},
error: function(xhr) {
console.log("Hata Oluştu...");
}
})

Use following code in the row
columns: [
{"data": "xxx", "width": "10%","visible": false, "render": function (data, type, row, meta) { } },
]
Use following code inside the function to make a clickable link on column
if (type === 'display') {
return $('<a>')
.attr('href', ' ')
.text(data)
.wrap('<div></div>')
.parent()
.html();
} else {
return data;
}

Related

Using the content of a variable returned by DataTables in another part of the script

How can I use the "DeviceID" in the "columns:" in another part of the script. I have tried all manner of things like re positioning some of the code but no matter what I do I can't get it to work.
I need to use the "DeviceID" as a variable in
"url: 'get_wayfinder_offline_status.php', data: { DeviceID: deviceid },"
Look at << USE THIS IN PART MARKED "HERE"
$(document).ready(function() {
var table = $('#WayFinderStatusTable').DataTable({
ordering: false,
paging: false,
searching: false,
bInfo: false,
responsive: true,
fixedHeader: true,
scrollX: false,
pageResize: true,
ajax: {
url: 'check_wayfinder_status.php',
dataSrc: ''
},
columns: [{
data: 'DisplayDescription',
"sWidth": "100%"
},
{
data: 'DeviceName',
"visible": false
},
{
data: 'MessageCount',
"visible": false
},
{
data: 'BoardOverride',
"visible": false
},
{
data: 'DeviceID',
"visible": false
}, // << USE THIS IN PART MAKED "HERE"
],
rowCallback: function(row, data, dataIndex) {
if (data.MessageCount == 2) {
$(row).find('td:eq(0)').addClass('WayFinderStatusTableOn HeaderStatusWayfinderRedTextBlink');
} else if (data.BoardOverride == 1) {
$(row).find('td:eq(0)').addClass('WayFinderStatusTableOverrideOn ');
$('#WayFinderStatusTable tbody').on('click', 'tr', function() {
var hotelid = "<?php echo $_SESSION['_amember_user']['hotelid'];?>";
var data = table.row(this).data();
var deviceid = data.DeviceID;
console.log("DEVICE ID", deviceid);
$.ajax({
url: 'get_wayfinder_override_status.php',
data: {
DeviceID: deviceid
},
type: 'POST',
dataType: 'JSON',
success: function(data) {
var result = JSON.stringify(data);
result = JSON.parse(result);
if (result.length > 0) {
console.log("BoardName", result);
$('#EditOverrideWayfinderRecordID').val(result[0]);
$('#EditOverrideWayfinderBoardName').val(result[1]);
var testimage = result[2];
console.log("TEST IMAGE", testimage);
$('#EditOverrideWayfinderImage').val(result[2]);
var imagepath = '../../../../conf/conf_images/override/' + hotelid + '/' + result[2];
$("#EditOverrideWayfinderLookUpCompanyImage").attr("src", imagepath);
$("#EditOverrideWayfinderImagePreview").attr("src", imagepath);
$('#EditOverrideWayfinderRoomFromDate').val(result[3]);
$('#EditOverrideWayfinderRoomFromTimeH').val(result[4]);
$('#EditOverrideWayfinderRoomFromTimeM').val(result[5]);
$('#EditOverrideWayfinderRoomToDate').val(result[6]);
$('#EditOverrideWayfinderRoomToTimeH').val(result[7]);
$('#EditOverrideWayfinderRoomToTimeM').val(result[8]);
$('#EditOverrideWayfinderPromotionName').val(result[9]);
$('#EditOverrideWayfinderHardwareID').val(result[10]);
$('#edit_wayfinder_override_data_modal').modal('show');
}
}
});
});
} else if (data.BoardOverride == "") {
$(row).find('td:eq(0)').addClass('WayFinderStatusTableOff');
}
},
});
$(document).on('click', '.WayFinderStatusTableOff', function(e) {
$('#wayfinder_override_data_modal').modal('show');
});
$(document).on('click', '.WayFinderStatusTableOn', function(e) {
console.log("OFFLINE CLICKED");
$.ajax({
url: 'get_wayfinder_offline_status.php',
data: {
DeviceID: deviceid //<<HERE
},
type: 'POST',
dataType: 'JSON',
success: function(data) {
var result = JSON.stringify(data);
result = JSON.parse(result);
if (result.length > 0) {
// DO SOMETHING
}
}
});
$('#offline_data_modal').modal('show');
});
setInterval(function() {
$('#WayFinderStatusTable').DataTable().ajax.reload();
}, 30000);
});
Based on structure of your datatables and column, clicked on a row the deviceId is find by using the method table.row( this ).data(); and next find the right index of the data.
$('#WayFinderStatusTable').on('click', 'tr', function () {
const data = table.row( this ).data();
const deviceId = data[4];
alert(deviceId + ' -> deviceid');
});

How to remove all items from a kendoListBox

I have two kendo list boxes they exchange items between them. Basically an Items available and an Items selected pair.
I have Json service which controls what items are available via a Json array.
When the user selects a new filter I want both Kendo List Boxes to clear the items out before adding the new items from the server.
Currently it appends the new list from the server to the current list.
$(document).ready(function () {
$("#filterKeyWord").click(function () {
getResults($("#keywords"));
});
$("#availableReports").kendoListBox({
dataTextField: "Name",
dataValueField: "ID",
connectWith: "selectedReports",
dropSources: ["availableReports"],
toolbar: {
tools: ["transferTo", "transferFrom", "transferAllTo", "transferAllFrom", "remove"]
}
});
$("#selectedReports").kendoListBox({
dataTextField: "Name",
dataValueField: "ID",
dropSources: ["selectedReports"],
remove: function (e) {
setSelected(e, false);
},
add: function (e) {
setSelected(e, true);
}
});
var mydata = { ReportName: "", UserId: "" };
mydata.ReportName = "SomeName";
mydata.UserId = "SomeUser";
var crudService = "",
dataSource = new kendo.data.DataSource({
serverFiltering: true,
transport: {
read: {
url: crudService + "GetReportList",
dataType: "json",
type: "get",
contentType: "application/json; charset=utf-8",
},
update: {
url: crudService + "SaveReportList2",
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "post",
},
filter: {
url: crudService + "GetReportList",
dataType: "json",
type: "get",
contentType: "application/json; charset=utf-8",
},
parameterMap: function (options, operation) {
console.log(operation);
if (operation !== "read" && options.models) {
return JSON.stringify({ models: options.models });
}
if (operation === "read") {
return "request=" + JSON.stringify(mydata);
}
}
},
batch: true,
requestStart: function () {
kendo.ui.progress($(".demo-section"), true);
console.log("request start");
},
requestEnd: function () {
kendo.ui.progress($(".demo-section"), false);
console.log("request end");
},
error: function (e) {
console.log("Error" + e);
},
change: function (e) {
console.log("change" + this.data.length);
setDropDownBoxes(this);
},
schema: {
model: {
id: "ID",
fields: {
ID: { type: "number" },
Selected: { type: "boolean" },
Name: { type: "string" },
Description: { type: "string" },
InternalId: { type: "string" }
}
}
}
});
$("#saveReportList").kendoButton({
click: function (e) {
dataSource.sync();
}
});
$("#getReportList").kendoButton({
click: function (e) {
mydata.ReportName = $("#keywords").val();
dataSource.read();
}
});
function setDropDownBoxes(obj) {
var data = obj.data();
var availableReports = $("#availableReports").data("kendoListBox");
var selectedReports = $("#selectedReports").data("kendoListBox");
var items = availableReports.dataItems();
for (var i = 0; i < data.length; i++) {
if (data[i].Selected) {
selectedReports.add(data[i]);
}
else {
availableReports.add(data[i]);
}
}
}
function setSelected(e, flag) {
var removedItems = e.dataItems;
for (var i = 0; i < removedItems.length; i++) {
console.log(flag + " " + removedItems[i].ID + " " + removedItems[i].Name + " " + removedItems[i].Selected);
var item = dataSource.get(removedItems[i].ID);
item.Selected = flag;
item.dirty = !item.dirty;
}
}
});
Not sure where in your exactly the clening should be performed, but, you can use both remove() and item() methods togheter to clear a listBox.
remove() method accepts a list of li elements, which is what items() returns, so it will remove the whole li collection from the list.
var listBox = $("#listBox").data("kendoListBox");
listBox.remove(listBox.items());
Demo

AJAX post data to DB without ASP:button

I retrieve a value in js and i want to insert it in the DB with ajax post. Is it possible to do that without asp:button to bind the value to the code behind?
UPDATE here is the Js:
function readXML() {
var xml = new XMLHttpRequest();
xml.open('GET', 'toXml/file.xml', false);
xml.send();
var xmlData = xml.responseXML;
if (!xmlData) {
xmlData = (new DOMParser()).parseFromString(xml.responseText, 'text/xml');
}
var itemsID = xmlData.getElementsByTagName("entry");
var itemsTitle = xmlData.getElementsByTagName("entry");
var itemsCustomer = xmlData.getElementsByTagName("d:Customer");
var itemsBrand = xmlData.getElementsByTagName("d:Brand");
var itemsCountries = xmlData.getElementsByTagName("d:Countries");
var itemsElement = xmlData.getElementsByTagName("d:element");
var i, k, j, ID, Title, Customer, Brand, Countries;
var list = [];
for (i = 0; i < itemsTitle.length; i++) {
var Brands = "";
var Country = "";
itemI = itemsID[i];
itemT = itemsTitle[i];
itemCr = itemsCustomer[i];
itemB = itemsBrand[i];
itemCs = itemsCountries[i];
itemEl = itemsElement[k];
ID = itemI.getElementsByTagName("d:Id")[0].firstChild.data;
Title = itemT.getElementsByTagName("d:Title")[0].firstChild.data;
Customer = itemCr.getElementsByTagName("d:element")[0].firstChild.data;
for (k = 0; k < itemB.children.length; k++) {
Brand = itemB.getElementsByTagName("d:element")[k].firstChild.data;
if (k > 1) {
Brands += Brand + ",";
}
else {
Brands = Brand;
}
}
for (j = 0; j < itemCs.children.length; j++) {
Countries = itemCs.getElementsByTagName("d:element")[j].firstChild.data;
if (j > 1) {
Country += Countries + ",";
}
else {
Country = Countries;
}
}
list[i] = [ID, Title, Customer, Brands, Country];
}
var table = $('#table_id').DataTable({
lengthMenu: [[10, 25, 50, 200, -1], [10, 25, 50, 200, "All"]],
data: list,
columns: [
{ title: "ID" },
{ title: "Title" },
{ title: "Customer" },
{ title: "Brands" },
{ title: "Country" },
{ title: "Check", "defaultContent": "<button class=\"checkBtn\" type=\"button\">Check</button>" },
{ title: "Create", "defaultContent": "<button class=\"createBtn\" type=\"button\">Create</button>" }
],
columnDefs: [{
"targets": [0],
"visible": true,
"searchable": true
}]
});
$('#table_id').on('click', '.checkBtn', function () {
var data = table.row($(this).parents('tr')).data();
alert("ID:" + data[0] + "," + "Title:" + data[1] + "," + "Customer:" + data[2] + "," + "Brand:" + data[3] + "," + "Country:" + data[4]);
$.ajax({
type: "POST",
url: "Selida.aspx/InsertData",
data: JSON.stringify(data[0]),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("all good");
},
error: function (errMessage) {
alert("Error:" + errMessage);
}
});
});
}
Through C# im getting data and i save it into an xml file. Then with the js i retrieve that data and with Jquery datatables im displaying on the page.
I Have a method in c# called InsertData which is supposed to insert the data in the DB. I think that the problem is in the ajax call.
The answer is yes, i can post a value from js with an ajax call that has no relation with the server side
$.ajax({
type: "POST",
url: "Selida.aspx/CheckData",
data: JSON.stringify({ trala : data[0] }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("It's already in the DB");
},
error: function (errMessage) {
console.log("Error:" + JSON.stringify(errMessage));
}
});
and the parameter in the c# method must have the name "trala" in order to retrieve the value from the post.

jquery server-side datatable not wroking properly

I added the server side jQuery data-table, Data from back-end coming correctly for all pagination, sorting etc. and also bind the data first time, but second time not replacing the content of data-table with new data.
Here is my JQuery code:
var table = $('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax":
{
"url": "View_account.aspx/GetData",
"contentType": "application/json",
"type": "GET",
"dataType": "JSON",
"data": function (d) {
return d;
},
"dataSrc": function (json) {
json.draw = json.d.draw;
json.recordsTotal = json.d.recordsTotal;
json.recordsFiltered = json.d.recordsFiltered;
json.data = json.d.data;
var return_data = json;
return return_data.data;
}
},
"columns": [
{
"data": "tblRow",
"render": function (data, type, row) {
console.log(data)
return data;
}
},
{ data: "cust_name" },
{ data: "status" },
{
data: "account_id",
"render": function (data, type, row) {
console.log(data)
return '<td><i class="fa fa-pencil edt_icn" aria-hidden="true"></i></td>';
}
},
{
data: "account_id",
"render": function (data, type, row) {
console.log(data)
return '<i class="fa fa-trash delet_wrpr delt_icn" aria-hidden="true"></i>';
}
},
{
data: ".account_id",
"render": function (data, type, row) {
console.log(data)
return "<input value='" + row.account_id + "' id='record" + row.account_id + "' name='record" + row.account_id + "' type='checkbox'>";
}
}
]
});
Please Help. Thank you in advance.
Try with "columnDefs"(datatables example) prop instead "columns" like:
var table = $('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax":
{
"url": "View_account.aspx/GetData",
"contentType": "application/json",
"type": "GET",
"dataType": "JSON",
"data": function (d) {
return d;
},
"dataSrc": function (json) {
json.draw = json.d.draw;
json.recordsTotal = json.d.recordsTotal;
json.recordsFiltered = json.d.recordsFiltered;
json.data = json.d.data;
var return_data = json;
return return_data.data;
}
},
// HERE CHANGE
"columnDefs": [
{
// HERE CHANGE ( COLUMN INDEX)
"targets": 0,
"render": function (data, type, row) {
console.log(data)
return data;
}
},
{
"targets": 3,
"render": function (data, type, row) {
console.log(data)
return '<td><i class="fa fa-pencil edt_icn" aria-hidden="true"></i></td>';
}
},
{
"targets": 4,
"render": function (data, type, row) {
console.log(data)
return '<i class="fa fa-trash delet_wrpr delt_icn" aria-hidden="true"></i>';
}
},
{
"targets": 5,
"render": function (data, type, row) {
console.log(data)
return "<input value='" + row.account_id + "' id='record" + row.account_id + "' name='record" + row.account_id + "' type='checkbox'>";
}
}
]
});

jqGrid row ordering by drag and drop

Is there any option for jqGrid row ordering by drag and drop ? I would like to save the order in DB. I have checked all existing solutions relatedto jqGrid drag & drop. But, nothing is working properly.
Here is my approach with ASP.NET MVC. But you should know that this easy to implement only if you don't have pager.
The main idea is to get all ids in your grid after drop and change item_order in your DB.
HTML
<table id="jqgTopMenu" cellpadding="0" cellspacing="0"></table>
<div id="jqgpTopMenu" style="text-align: center;"></div>
Script
$('#jqgTopMenu').jqGrid({
url: '#Url.Action("TopMenus")',
datatype: 'json',
mtype: 'POST',
colNames: ['Id', 'ItemOrder', 'Name', 'Short name'],
colModel: [
{ name: 'Id', index: 'Id', hidden: true },
{ name: 'ItemOrder', index: 'ItemOrder', hidden: true },
{ name: 'PostName', index: 'PostName', align: 'left', width: 430 },
{ name: 'PostNameShort', index: 'PostNameShort', align: 'left', width: 500 },
],
});
//sort Part
$('#jqgTopMenu').jqGrid('sortableRows',
{
update: function (e, ui) {
var ids = $("#jqgTopMenu").jqGrid('getDataIDs');
$.ajaxSettings.traditional = true;
$.ajax({
url: '#Url.Action("SortTopMenu","Admin")',
type: 'post',
dataType: 'json',
data: { ids: ids },
success: function (data) {
$('#jqgTopMenu').trigger("reloadGrid")
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("status: " + textStatus + " Error: " + errorThrown);
}
});
}
});
Controller
[HttpPost]
public JsonResult SortTopMenu(List<int> ids)
{
return Json(_dataManager.TopMenu.Sort(ids));
}
Manager DB method
public bool Sort(List<int> ids)
{
for (int i = 0; i < ids.Count; i++)
{
top_menu t = _dataContext.top_menu.FirstOrDefault(tm => tm.id == ids[i]);
t.item_order = i;
_dataContext.SubmitChanges();
}
return true;
}

Categories