Datatables - Why row() method can not get index value? - javascript

here is my code (and ajax data) to insert index column to table. But I don't know why console log don't see the index value. I tried searching solution but couldn't find it. Someone please help me, thanks you so much.
<!DOCTYPE html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.11.5/datatables.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/css/bootstrap.min.css">
<link type="text/css" rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css" />
<script>
$(function () {
var table = $('#example').DataTable({
ajax: '../ajax/data/objects_salary.txt',
columns: [
{
"render": function (data, type, full, meta) {
return meta.row + 1;
}
},
{ data: 'name' },
{ data: 'position' },
{ data: 'office' },
{ data: 'extn' },
{ data: "start_date" },
{ data: "salary" }
]
});
$('#example tbody').on('click', 'tr', function () {
var data = table.row(this).data();
console.log(data);
});
});
</script>
</head>
<body>
<div class="container mt-4 bt-4">
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Index</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Progress</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
</table>
</div>
</body>
</html>
Console log output
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "320800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
}

That's because the meta.row index is NOT part of the ajax data for the table. table.data() shows only the data (i.e., what you set in the data key of columns[] initialization option.)
Indeed, meta.row is just an index you're rendering via the meta object that - according to the Docs - is:
An object that contains additional information about the cell being
requested. This object contains the following properties (...etc)
try this:
$('#example tbody').on('click', 'tr', function () {
const data = dt.row(this).data();
const index = dt.row(this).index() + 1;
const rowData = {...data, index};
console.log(rowData);
});
P.S. var is legacy Javascript, use const / let instead (unless you've really good reasons to use var)

I suggest changing the id to something else, ex. salary_id. if that doesn't work can you also upload your objects_salary.txt

Related

extracting values from rows to use in a URL

I have generated a data table using the Datatables jquery plugin. The table is populated with JSON.
I want to extract cell values when I make a selection to use in a URL but I can't get it to work.
#I'm using django
import json
#my list
users = [[1,26,'John','Smith'],[2,33,'Dave','Johnson'],[1,22,'Aaron','Jones']]
#my json
user_json = json.dumps(users)
<table class="table table-striped- table-bordered table-hover table-checkable" id="user-table">
<thead>
<tr>
<th>Age</th>
<th>Record ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Actions</th>
</tr>
</thead>
</table>
<script type="text/javascript">
var userData = {{user_json|safe}};
</script>
var SourceHtml = function() {
var dataJSONArray = userData;
var initTable1 = function() {
var table = $('#user-table');
// begin table
table.DataTable({
responsive: true,
data: dataJSONArray,
columnDefs: [
{
targets: -1,
title: 'Actions',
orderable: false,
render: function(data, type, full, meta) {
//this is where I need help. I need for each a-tag to link to a django url pattern such as href="{% url 'users:select-user' id=id_value %}"
return '<i class="la la-edit"></i>';
},
},
],
});
};
return {
//main function to initiate the module
init: function() {
initTable1();
}
};
}();
jQuery(document).ready(function() {
SourceHtml.init();
});
I need a href link to a django url pattern such as href="{% url 'users:select-user' id=id_value %}" in each a tag. however, I can't get the values from the cells.
Datatables columns.render option can be used to access full data source of current row.
By using columns.render as function type, we can use third (3)
parameter to access another column index form same row of data
source.
var userData = [[1,26,'John','Smith'],[2,33,'Dave','Johnson'],[1,22,'Aaron','Jones']];
$('#example').dataTable( {
"columnDefs": [ {
"targets": -1,
"data": null,
"title": 'Actions',
"render": function ( data, type, row, meta ) {
return 'Download';
}
} ]
} );

How to display json array coming from url through ajax in angularjs

I have a json array coming from a url:
http://blahblahblah.com/company/all, like this:
in angularjs controller, i have something like this:
$('#example-1').DataTable({
"ajax" : 'http://blahblahblah.com/company/all',
"columns": [
{"data": "companyId"},
{.....}, // I can't assign "data" name to array because it is already unnamed.
]
});
Traversing in html table_id example-1
<table id="example-1" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Company</th>
<th>Legal Name</th>
<th>DBA Name</th>
<th>Formation</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Company</th>
<th>Legal Name</th>
<th>DBA Name</th>
<th>Formation</th>
</tr>
</tfoot>
Output:
So, my question is how do I identify the column names from above UNNAMED JSON ARRAY mentioned on top of the question, and display it in html table. Waiting for your kind response.
I am thinking to do something like this
$(document).ready(function() {
$('#example').DataTable( {
"ajax": "http://blahblahblah.com/company/all",
"columns": [
{ "data": "companyId" },
{ "data": "legalName" },
{ "data": "dbaName" },
{ "data": "formation"}
]
} );
} );
you need to add more information to the datatable while intializing what are the keys to be shown. form more details check datatable objects
I was unable to identify the correct syntax of identifying and using the column names in my JSON array, which I did like this, and solved my problem. So now the data is displayed fine in my table, this way:
$.getJSON('http://blahblahblah/company/all', function(data) {
$('#companies').DataTable({
"aaData": data,
"aoColumns": [
{"mDataProp":"companyId"},
{"mDataProp":"legalName"},
{"mDataProp":"dbaName"},
{"mDataProp":"formation"}
]
});
});
I also added hyperlink to companyId like this:
$.getJSON('http://blahblahblah/company/all', function(data) {
var companyId = null;
$('#companies').DataTable({
"aaData": data,
"aoColumns": [
{"mDataProp":"companyId", "render": function(data, type, row, meta) {
if( type==='display' ) {
companyId = data;
data = '' + data + '';
}
return data;
}},
{"mDataProp":"legalName"},
{"mDataProp":"dbaName"},
{"mDataProp":"formation"}
]
});
});
I am thankful to all of you for helping me grab the track.
Thanks.
Actual way to do this is to use ng-repeat in the data array. And for the data fetch, use an angular service with a promise.
In the Controller
var self = this;// this is the controller which is aliased as ctrl at routing
var theData = yourService.FetchData(params).then(function(data){
self.tableData = data; // not going for the exact implementation.
},function(err){
manageError(err);// manage your errors here.
}));
In the HTML
<table id="example-1" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Company</th>
<th>Legal Name</th>
<th>DBA Name</th>
<th>Formation</th>
</tr>
</thead>
<tr ng-repeat="var item in ctrl.tableData ">
<td>{{item.companyId}}</td>
<td>{{item.legalName}}</td>
<td>{{item.dbaName}}</td>
<td>{{item.formation}}</td>
</tr>
</table>

Render complicated Array into Datatables

I Have a really complicated Array that I want to display in DataTables in order to do some research and csv export.
An extract here of one page : https://api.myjson.com/bins/w8pzl
This is the structure :
[
[
{
title : "title",
stacks: {
stackname : "stackname",
stackValue : [
"value1","value2","value3"
]
},
..... multiple article
],
.....multiple pages
]
I don't know neither how to structure the table nor how to populate it.
My first try so far :
<div id="page-content-wrapper">
<div class="container">
<div class="row">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Stackname</th>
<th>stackvalue</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('#example').DataTable({
"processing" : true,
"ajax" : {
"url" : "/",
dataSrc : ''
},
"columns" : [ {
"data" : "stackName"
}, {
"data" : "stackValue[,]"
}]
});
});
</script>
But it looks like I have to go through the all document to get my information..
If it's just not possible... I've done an easier version of my structure :
[
[
{
title : "title",
stacks: [
"value1","value2","value3"
]
},
..... multiple article
],
.....multiple pages
]
But still impossible to parse it.. i'm struggling with the two first array..
Edit with answer
Thanks to the help of the selected answer post I managed to get this code working :
$('#example').DataTable( {
"processing" : true,
"ajax": {
"url": "/",
"dataSrc" : function ( json ) {
return json.reduce(function(a, b) {
return a.concat(b)
}).map(function(value) {
return value.stacks
})
.reduce(function(a, b) {
return a.concat(b)
})
}
}
,... other configuration
You can use the ajax.dataSrc option as a function to manipulate the data returned from the server.
ajax.dataSrc
function ajax.dataSrc( data )
As a function dataSrc provides the ability to manipulate the data returned from the server from one form into another. For example, if your data is split over multiple arrays you might combine it into a single array to return for processing and display by DataTables. ...
Here is an example.
$('#example').DataTable( {
"ajax": {
"url": "https://api.myjson.com/bins/w8pzl",
"dataSrc" : function ( json ) {
return json[0].map(function(value) {
return value.stacks
})
.reduce(function(a, b) {
return a.concat(b)
})
}
},
"columns": [
{ "data": "stackName" },
{ "data": "stackValue[, ]" }
]
});
<link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Stackname</th>
<th>stackvalue</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Stackname</th>
<th>stackvalue</th>
</tr>
</tfoot>
</table>

query.dataTables.min.js - Uncaught TypeError: Cannot read property 'length' of undefined

I am new at JSon and have been searching all over the internet but can't find out where is the error. Can you help me, please? The controller returns the object but nothing is displayed, and it comes out an error saying "Cannot read property 'length' of undefined"`.
This is my main template file:
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-theme.min.css" rel="stylesheet" />
<script src="~/scripts/jquery-1.9.1.js"></script>
<script src="~/scripts/bootstrap.min.js"></script>
<!-- Data table -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.10/css/dataTables.bootstrap.min.css " />
<script src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="https://cdn.datatables.net/1.10.10/js/dataTables.bootstrap.min.js" type="text/javascript"></script>
This is my table:
<table class="table table-bordered" id="tabela">
<thead>
<tr>
<th>Nome</th>
<th>Quantidade</th>
<th>Preco</th>
<th></th>
</tr>
</thead>
</table>
This is my JSon:
$('#tabela').DataTable({
"columnDefs": [
{ "width": "5%", "targets": [0] }, {
"className": "text-center custom-middle-align",
"targets": [0, 1, 2, 3]
},
],
"language": {
"processing": "<div class='overlay custom-loader-background'><i class='fa fa-cog fa-spin custom-loader-color'></i></div>"
},
"processing": true,
"serverSide": true,
"ajax": {
"url": "/produto/BuscarTodos",
"type": "POST",
"dataType": "JSON"
},
"columns": [{
"data": "Nome"
}, {
"data": "Preco"
}, {
"data": "Quantidade"
}, {
"data": "IdProduto"
}, ]
});
This is my controller:
public JsonResult BuscarTodos()
{
try
{
string dados = "";
// Initialization.
string search = Request.Form.GetValues("search[value]")[0];
string draw = Request.Form.GetValues("draw")[0];
string order = Request.Form.GetValues("order[0][column]")[0];
string orderDir = Request.Form.GetValues("order[0][dir]")[0];
int startRec = Convert.ToInt32(Request.Form.GetValues("start")[0]);
int pageSize = Convert.ToInt32(Request.Form.GetValues("length")[0]);
ProdutoConexao con = new ProdutoConexao();
List<Produto> lista = new List<Produto>();
lista = con.FindAll();
// Total record count.
int totalRecords = lista.Count;
if (!string.IsNullOrEmpty(search) && !string.IsNullOrWhiteSpace(search))
{
// Apply search
lista = lista.Where(p => p.Nome.ToLower().Contains(search.ToLower())).ToList();
}
// Sorting.
lista = this.SortByColumnWithOrder(order, orderDir, lista);
// Filter record count.
int recFilter = lista.Count;
// Apply pagination.
lista = lista.Skip(startRec).Take(pageSize).ToList();
// Loading drop down lists.
var result = this.Json(new
{
draw = Convert.ToInt32(draw),
recordsTotal = totalRecords,
recordsFiltered = recFilter,
data = lista
}, JsonRequestBehavior.AllowGet);
return Json(result);
}
catch (Exception ex)
{
return Json(ex);
}
}
private List<Produto> SortByColumnWithOrder(string order, string orderDir, List<Produto> data)
{
// Initialization.
List<Produto> lista = new List<Produto>();
try
{
// Sorting
switch (order)
{
case "0":
// Setting.
lista = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(p => p.Nome).ToList() : data.OrderBy(p => p.Nome).ToList();
break;
}
catch (Exception ex)
{
// info.
Console.Write(ex);
}
// info.
return lista;
}
Just to check that your datatable setup is up and correct I will suggest to create an empty table (no controller) just to make sure that you have everything setup correctly. If that works I'll add your controller and dynamic data.
Datatables REQUIRE a specific HTML table format if it can't find it then you'll get that error.
The simplest table you can check with is the following:
<table>
<thead>
<tr>
<th>header 1</th>
</tr>
</thead>
<tbody>
<tr>
<td>Content 1</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Footer 1</td>
</tr>
</tfoot>
The footer is optional, everything else is required.
EDIT 1:
Take a look at the similar example they posted

Getting an error "Is null or not an object"

I have the following code:
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body>
<table class="table" id="table_id">
<thead>
<th data-dynatable-column="pt_name">Name</th>
<th data-dynatable-column="unit">Unit</th>
<th data-dynatable-column="room">Room</th>
<th data-dynatable-column="fin">FIN</th>
<th data-dynatable-column="line_type">Line Type</th>
<th data-dynatable-column="line_loc">Location</th>
<th data-dynatable-column="line_days">Est Days in Place</th>
<th data-dynatable-column="insert_date">Insertion Date</th>
<th data-dynatable-column="last_dsg_change">Last Dsg Change</th>
<th data-dynatable-column="hosp_insertion">Hospital Insert</th>
<th data-dynatable-column="reason">Reason</th>
</thead>
<tbody></tbody>
</table>
<script src="//cdnjs.cloudflare.com/ajax/libs/json2/20130526/json2.min.js"></script>
<script type="text/javascript" charset="utf8" src="js/jquery-1.11.1.min.js"></script>
<script src="libs/jquery-dynatable/jquery.dynatable.js"></script>
<script>
$(function(){
$.get("model/20_mp_cc_get_cvcs.json",function (data) {
$('#table_id').dynatable({
dataset: {
records: data.cvc_list.qual
}
});
})
});
</script>
</body>
</html>
and a portion of the 20_mp_cc_get_cvcs.json is:
{
"cvc_list": {
"cvc_cnt": 12,
"patient_cnt": 6,
"qual": [
{
"dg_id": 20627424964.0,
"enc_id": 82048822.0,
"fin": "700001703",
"hosp_insertion": "y",
"insert_date": "05/29/2014",
"insert_dt_tm": "/date(2014-05-29t00:00:00.000-04:00)/",
"last_dsg_change": "",
"line_days": 31,
"line_loc": "upper",
"line_type": "cvc",
"pers_id": 69935620.0,
"pt_name": "buildtest , domainone",
"reason": "",
"room": "1rmh",
"unit": "1rmh"
},
{
"dg_id": 20627428586.0,
"enc_id": 82048822.0,
"fin": "700001703",
"hosp_insertion": "n",
"insert_date": "05/21/2014",
"insert_dt_tm": "/date(2014-05-21t00:00:00.000-04:00)/",
"last_dsg_change": "",
"line_days": 39,
"line_loc": "rt., brachial",
"line_type": "picc",
"pers_id": 69935620.0,
"pt_name": "buildtest , domainone",
"reason": "",
"room": "1rmh",
"unit": "1rmh"
}
]
}
}
I keep getting an error that says cvc_list.qual is "null or not an object". This is not happening in all browsers. Just in our Citrix VM running IE10 with Document Mode IE7. What might I be doing wrong?
$.get might not gurantee a JSON parse, better to use the full version -
$(function(){
$.ajax({
url: "model/20_mp_cc_get_cvcs.json",
dataType: "json",
type: "get",
success: function(data){
$('#table_id').dynatable({
dataset: {
records: data.cvc_list.qual
}
});
}
});
});
There is also a JSON.parse method available in IE7, so you can also use that one to parse on your side. So you might do something like this -
$.get("model/20_mp_cc_get_cvcs.json",function (data) {
if (typeof data == "string"){
data = JSON.parse(data);
}
$('#table_id').dynatable({
dataset: {
records: data.cvc_list.qual
}
});
})
Use dataType attribute in your ajax call.
As per jQuery docs, by default its value is evaluated based on guess;
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String The type of data that you're expecting back from the
server. If none is specified, jQuery will try to infer it based on the
MIME type of the response (an XML MIME type will yield XML, in 1.4
JSON will yield a JavaScript object, in 1.4 script will execute the
script, and anything else will be returned as a string).
Specify dataType : json in your ajax call if you are expecting a json from server side.
Or alternatively you can use, jQuery.parseJson
Sol#1
$.get("model/20_mp_cc_get_cvcs.json",function (data) {
$('#table_id').dynatable({
dataset: {
records: data.cvc_list.qual
}
});
}, "json"); // Tell jQuery that you are expecting json.
Sol#2
$.get("model/20_mp_cc_get_cvcs.json", function (data) {
var json = jQuery.parseJSON(data); // parse it
$('#table_id').dynatable({
dataset: {
records: json.cvc_list.qual // use the json here
}
});
});

Categories

Resources