Unable to get row data in datatables - javascript

I am try to get the complete row data on click.
I tried this code from Datatables official website -
var table = $('#example').DataTable( {
data: data,
columns: [
{ data: "UserID" },
{ data: "Name" },
{ data: "emailID" },
{ data: "Role" },
{ data: "Status" }
]
} );
$('#example tbody').on( 'click', 'tr', function () {
var data = table.row(this).data();
alert( "Value = "+data[0] );
} );
But getting the Value = undefined.

Solution for this is -
Instead of -
alert( "Value = "+ data[0] );
We have to access it in this way because its an object -
alert( "Value = "+ data.UserID );

Initialize table object like this:
var table = $('#example').DataTable();

Related

How to pass multiple parameters in columns.render function in Datatables jquery?

I have data below and I want to pass two variables (id, name) in the columns.render function in Datatables.
What I have now is only pass the id in the render function.
I also want to pass name in the render function.
Thanks.
const myData = [
{ id: 2, name: "book" },
{ id: 5, name: "song" },
];
$("#example").DataTable({
data: myData,
columns: [
{
targets: 1,
data: "id",
render: function (data, type, row, meta) {
return (
"<button class='btn btn-default' data_id='" +
data + //id is passed to here
"'>" +
"name" + //the name I want to pass to here.
"</button>"
);
},
},
],
});
You can do it using the row parameter of render function.
const myData = [
{ id: 2, name: "book" },
{ id: 5, name: "song" },
];
$("#example").DataTable({
data: myData,
columns: [
{
targets: 1,
data: "id",
render: function (data, type, row, meta) {
return (
"<button class='btn btn-default' data_id='" +
data + //id is passed to here
"'>" +
row.name + //get the name using row parameter
"</button>"
);
},
},
],
});
More details about render function can be found at https://datatables.net/reference/option/columns.render

Populating slickgrid(JS) with PHP array

I have this huge slickgrid that users can fill with data. once filled in the data is sent to the server-side with AJAX and then to the database with PHP. then I get the data out of the database and put it inside a PHP array. Now how do I populate the slickgrid with that array data. I cant seem to find the solution to this. because How to I get that php array inside the javascript slickgrid file.
javascript slickgrid for information:
<script type ='text/javascript'>
var gridArray;
var editedRows = []
function CreateColumns() {
var columns = [
{id: "hours", name: "uren", field: "hours"},
{id: "Total_inspection", name: "totaal inspectie", field: "Total_inspection", editor: Slick.Editors.Integer},
{id: "Per_hour_inspection", name: "Per uur", field: "Per_hour_inspection"},
{id: "Total_losses", name: "Totaal uitstoot", field: "Total_losses",editor: Slick.Editors.Integer},
{id: "Per_hour_losses", name: "Per uur", field: "Per_hour_losses"},
{id: "%_spil", name: "% Spil", field: "%_spil"},
{id: "%_cumul", name: "% Cumul", field: "%_cumul"},
{id: "Operator", name: "Operator", field: "Operator",editor: Slick.Editors.Text},
{id: "SKU", name: "SKU", field: "SKU",editor: Slick.Editors.Text},
{id: "End_SKU", name: "Tellerstand einde SKU", field: "End_SKU"},
{id: "Batch", name: "Batch", field: "Batch"}
];
return columns;
}
function CreateOptions() {
var options = {
editable: true,
enableCellNavigation: true,
enableColumnReorder: false,
autoEdit :false
};
return options;
}
var data = [];
function CreateData() {
for (var i = 0; i < 8; i++) {
data[i] = {
hours: 6+i+"U",
};
}
return data;
}
console.log(data)
function CreateGrid(elementId) {
if (!gridArray) { gridArray = []; }
var data = CreateData();
//editedRows.push(data)
var grid = new Slick.Grid("#" + elementId,data, CreateColumns(), CreateOptions());
gridArray[length] = grid;
//todo tets localstorage
var columnidx = data[0].Total_inspection
var columnidx2 = data[0].Total_losses
var calculation = columnidx2/columnidx
var columnidx3 = data[0].Per_hour_inspection
//push(calculation)
var columnid = data[columnidx]
//console.log(calculation,columnidx3)
grid.onCellChange.subscribe(function (e,args) {
//console.log('arguments',args.item);
editedRows.push(args.item)
console.log('arrayrows',editedRows)
});
}
console.log(editedRows)
$('#Savebtn').click(function () {
console.log(editedRows);
//var UpdatedRows = JSON.stringify(editedRows);
//console.log(UpdatedRows);
$.ajax({
type: "POST",
url: "request.php",// changed
data: {arrayOfValues: editedRows},
success: function (data) {
// here comes your response after calling the server
alert('Suceeded');
alert(data)
console.log(data)
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error : " + jqXHR.responseText);
}
});
});
PHP looks like this :
$stmt = $mysqli->prepare("SELECT * FROM kicdata");
//$stmt->bind_param('i',$id);
$stmt->execute();
$result = $stmt->get_result();
$return_data = [];
while($row = $result->fetch_assoc()){
$return_data[]= $row;
}
var_dump($return_data);
UPDATE: the use of ajax solved the part to send the server-side array to the client-side.

Easy Autocomplete nested Json structure

I'm having a hard time to structure the list location for items array in order to access name attribute in search.js
Below is the nested JSON structure:
{
menus: [
{
name: "Summer ",
url: "/menus/2",
items: [
{
name: "man o man", //this is what I'm trying to access
url: "/menus/2/items/7"
}
]
]
}
So far I've tried in search.js:
document.addEventListener("turbolinks:load", function() {
$input = $("[data-behavior='autocomplete']")
var options = {
getValue: "name",
url: function(phrase) {
data = "/search.json?q=" + phrase;
return data;
},
categories: [
{
listLocation: "menus",
header: "--<strong>Menus</strong>--",
},
{
listLocation: "items", //this is where I'm having problem with
header: "--<strong>Items</strong>--",
}
],
list: {
onChooseEvent: function() {
var url = $input.getSelectedItemData().url
$input.val("")
Turbolinks.visit(url)
}
}
}
$input.easyAutocomplete(options)
})

jQuery Autocomplete showing result label as undefined

The list is being filtered properly but the label is showing as undefined. When I select the item, the value is binded.
Below is my code along with the screenshots:
$(document).on('ready',function(){
$('#search').autocomplete({
source: function(req,res) {
$.ajax({
url: "/search",
dataType: "json",
type: "GET",
data: {
term: req.term
},
success: function(data) {
res($.map(data, function(item) {
return {
label: item.name,
value: item.id
};
}));
},
error: function(xhr) {
alert(xhr.status + ' : ' + xhr.statusText);
}
});
},
select: function(event, ui) {
}
});
});
Before Selection
After selection
I tried debugging the label and value using alert function. The values are perfect. I'm unable to figure out the error.
item.name
item.id
Here is the callback response:
[
{
"id":"1",
"name":"Android"
},
{
"id":"2",
"name":"Akira"
},
{
"id":"3",
"name":"Andy"
},
....
]
You are returning different property names in ajax success function.
Can you try to use these property names instead.
[
{
"label":"1",
"value":"Android"
},
....
]
$.ajax({
url: "url",
type: 'POST',
data: {
},
success: function (res) {
//console.log(res);
var obj = JSON.parse(res);
$('#od').html('<option value=""> Select</option>');
for (var i = 0, len = obj.length; i < len; i++){
$('#id').append('<option value='+ obj[i].item_id +'> '+ obj[i].item_name +'</option>');
}
}
});
here is my code for get all option you can try this

dynamic columnDef in ng-Grid

I want to assign ng-grid columns name dynamically after value returned from database, but issue is that it get initialized before data return from ajax, and i am not able to recall gridOption so it showing balnk, so please help me that how can we construct a column name by ajax return value.
$scope.gridOptions =
{
data: 'data.Values',
columnDefs:
[
{ field: "ID", displayName: "Record Id" },
{ field: "Value", displayName: $scope.ColumnName, cellFilter: cellfilterType },
],
};
where $scope.ColumnName coming from below line...
RecordService.getRecords().then(function (data) {
$scope.ColumnName= data.something;
}
Thanks
Thanks Max for your help, I have done this with of help columnDef as below:
Step 1:
$scope.colDef = [];
Step 2:
RecordService.getRecords().then(function (data){
$scope.colDef=["ColumnName":data.something]
}
Step 3:
$scope.gridOptions = {
data: 'data.UdiValues',
columnDefs:'colDef',
filterOptions: $scope.filterOptions
};
Try to set first "default" value and after change it with promise
$scope.gridOptions =
{
data: 'data.Values',
columnDefs:
[
{
field: "ID",
displayName: "Record Id"
},
{ field: "Value",
displayName: "default",
cellFilter: cellfilterType
},
]
};
And now:
RecordService.getRecords().then(function (data) {
$scope.gridOptions.columnDefs[1].displayName = data.something;
}
The Service RecordService returns promise therefore we create promise factory like:
.factory('RecordService', ['$resource','$q', function($resource, $q) {
var data = { something: "from service" } ;
var factory = {
getRecords: function (selectedSubject) {
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
}
return factory;
}]);
Demo Fiddle
Something like this
Return json, play around, use GET mapping to strings etc?
i have done something like this :-
self.gridOptions.columnDefs = columnDefs(colDef,displayNames);
columnDef is :-
var columnDefs = function(data,cd){
var colDef= [];
var mi = null;
var colByOrder = sortedByOrder(data);
for(var i=0 ; i < colByOrder.length ; i++){
colDef.push({
width: width,
field: String(colByOrder[i][1].position),
menuItems: menuItems(this),
displayName: cd[colByOrder[i][1].position],
enableSorting: false,
type: 'string',
});
}
return colDef;
};

Categories

Resources