extracting values from rows to use in a URL - javascript

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';
}
} ]
} );

Related

Datatable for pagination and searching for live data?

I tried using datatables for live data but my problem is, every time my data updates, I can't use searching and every time I use pagination, it goes back to first page. Can somebody knows what datatable plugin is compatible with angular?
Here is my code for realtime update of data:
angular.module('selectExample', [])
.controller('ExampleController', ['$scope','$interval', function($scope,$interval) {
$interval(function () {
$scope.register = {
regData: {
branch: {},
},
names: [
{name:"narquois"},{name:"vorpal"},{name:"keen"},
{name:"argol"},{name:"long"},{name:"propolis"},
{name:"bees"},{name:"film"},{name:"dipsetic"},
{name:"thirsty"},{name:"opacity"},{name:"simplex"},
{name:"jurel"},{name:"coastal "},{name:"fish"},
{name:"kraken"},{name:"woman"},{name:"limp"},
],
};
}, 1000);
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="selectExample" ng-controller="ExampleController">
<table id="example" width="100%">
<thead>
<tr align="center">
<th>Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in register.names">
<td align="center">{{ person.name }}</td>
</tr>
</tbody>
</table>
</div>
Enable state saving and override state save/load handlers to use only the table's DOM id:
$('#example').dataTable( {
stateSave: true,
stateSaveCallback: function(settings,data) {
localStorage.setItem( 'DataTables_' + settings.sInstance, JSON.stringify(data) )
},
stateLoadCallback: function(settings) {
return JSON.parse( localStorage.getItem( 'DataTables_' + settings.sInstance ) )
}
} );
You have to initialize your DataTable with the option stateSave. It enables you to keep the pagination, filter values, and sorting of your table on page refresh. It uses HTML5's APIs localStorage and sessionStorage.
$('#example').dataTable( {
stateSave: true
});

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>

Core 2 MVC with JQuery Datatables

There is a good example on how to use JQuery Datatables with Core MVC at Using jQuery DataTables Grid With ASP.NET CORE MVC
I download the sample project, made some modifications and it works perfectly.
However, I'm getting an error when I try to integrate this into my project.
DataTables warning: table id=example - Requested unknown parameter 'IdStudent' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
After I click ok on the error, the table generates with the correct number of rows, but with no data:
This is my class:
public class GridStudent
{
[Key]
public int IdStudent { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
}
The HTML and JavaScript:
<div class="container">
<br />
<div style="width:90%; margin:0 auto;">
<table id="example" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
<thead>
<tr>
<th>IdStudent</th>
<th>Name</th>
<th>LastName</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
</table>
</div>
</div>
<script>
$(document).ready(function ()
{
$("#example").DataTable({
"processing": true, // for show progress bar
"serverSide": true, // for process server side
"filter": true, // this is for disable filter (search box)
"orderMulti": false, // for disable multiple column at once
"ajax": {
"url": "/StudentGrid/LoadData",
"type": "POST",
"datatype": "json"
},
"columnDefs":
[
{
"targets": [0],
"visible": false,
"searchable": false,
}
],
"columns": [
{ "data": "IdStudent", "name": "IdStudent", "autoWidth": true },
{ "data": "Name", "name": "Name", "autoWidth": true },
{ "data": "LastName", "name": "LastName", "autoWidth": true },
{
"render": function (data, type, full, meta)
{ return '<a class="btn btn-info" href="/StudentGrid/Edit/' + full.IdStudent + '">Edit</a>'; }
}
,
{
data: null, render: function (data, type, row)
{
return "<a href='#' class='btn btn-danger' onclick=DeleteData('" + row.IdStudent + "'); >Delete</a>";
}
},
]
});
});
function DeleteData(CustomerID)
{
if (confirm("Are you sure you want to delete ...?"))
{
Delete(CustomerID);
}
else
{
return false;
}
}
function Delete(CustomerID)
{
var url = '#Url.Content("~/")' + "StudentGrid/Delete";
$.post(url, { ID: CustomerID }, function (data)
{
if (data)
{
oTable = $('#example').DataTable();
oTable.draw();
}
else
{
alert("Something Went Wrong!");
}
});
}
</script>
This is the line of code, from the controller, than returns the data:
return await Task.Run(() => Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data }));
As you can see from the image, the controller is returning the data correctly, but for some reason DataTables can't read it.
I cross check with the sample a thousand times and I can't see a difference on the format of the data being return.
Any suggestions?
This is most likely due to the casing of the serialized JSON. Your data properties in the column definitions within your JavaScript expect Pascal casing. At present, I expect your are serializing JSON as lower camel case rather than Pascal case (e.g. idStudent instead of IdStudent).
To serialize JSON as Pascal case, make sure you have the following in the ConfigureServices method in your Startup class:
services
.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver
= new Newtonsoft.Json.Serialization.DefaultContractResolver();
});

Add href hyperlink to row or field in datatable

I've seen a lot of questions about this, however I cannot seem to get it working.
I have a datatable but I cannot get it to work. I use python-flask with bootstrap and I change a pandas dataframe to a html table with to_html().
<table width="100%" class="table table-striped table-bordered table-hover dataTable" id="dataTables-example"><thead>
<tr style="text-align: right;">
<th>id</th>
<th>user</th>
<th>status</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>1</td>
</tr>
</tbody>
</table>
and at the bottom of the body I have:
<script>
$(document).ready(function() {
$('#dataTables-example').DataTable({
"bDestroy": true,
"deferRender": true,
"columns": [
{ "data": "id" },
{
"data": "weblink",
"render" : function(data, type, row, meta){
if(type === 'display'){
return $('<a>')
.attr('href', data)
.text(data)
.wrap('<div></div>')
.parent()
.html();
} else {
return data;
}
}
}
]
});
});
</script>
I've looked at a lot of awnsers however they all contain the data as json in the javascript while my data is already in the html.
Use columnDefs when you have a DOM <table> and only need to target one or few columns :
$('#dataTables-example').DataTable({
destroy: true,
deferRender: true,
columnDefs: [{
targets: 0, //<-- index of column that should be rendered as link
render : function(data, type, row, meta){
if (type === 'display'){
return $('<a>')
.attr('href', data)
.text(data)
.wrap('<div></div>')
.parent()
.html();
} else {
return data;
}
}
}]
})
It works here -> http://jsfiddle.net/j9ez0sbj/
You have 3 columns in your html table but only define 2 columns in your initialization.
From datatables documentation for the columns initialization option:
Note that if you use columns to define your columns, you must have an entry in the array for every single column that you have in your table (these can be null if you don't wish to specify any options).
Depending on what your intent is, at the very least you need to add a definition for the third column, so something like this:
"columns": [
{ "data": "id" },
{
"data": "weblink",
"render" : function(data, type, row, meta){
if(type === 'display'){
return $('<a>')
.attr('href', data)
.text(data)
.wrap('<div></div>')
.parent()
.html();
} else {
return data;
}
}
},
{ "data": "status" } // Third column definition added
]

Jquery Datatables How to get column Id in render function

I'm trying to create a reference into the row cell.
This is my code:
<table class="table table-striped table-bordered table-hover little_margin_table" id="data-table" width="100%">
<thead>
<th>First Name</th>
<th>Email</th>
<th>Password</th>
</thead>
<tbody>
#foreach (var item in Model.Items)
{
<tr id="#item.Id">
<td>#item.FirstName</td>
<td>#item.Email</td>
<td>#item.Password</td>
</tr>
}
</tbody>
</table>
Javascript code:
$(document).ready(function () {
$('#data-table').dataTable({
bFilter: false,
aoColumnDefs: [
{
bSortable: false,
aTargets: [1, 2],
},
{
"targets": 0,
"render": function (data, type, full, meta) {
return '<a href = "#(Url.Action("IndexPage", "Company"))/' + ROWID '</a>';
}
},
]
})
Here I am assuming the row Id :
<tr id="#item.Id">
How can get it to into the function render:
"render": function (data, type, full, meta) {
return '<a href = "#(Url.Action("IndexPage", "Company"))/' + ROWID '</a>';
Help, please.
You could add a extra column to your table:
<td>#item.FirstName</td>
<td>#item.Email</td>
<td>#item.Password</td>
<td>#item.Id</td>
Which is set to hidden in the datatables init code:
'bVisible': false
When you use render you can now get the Id value from full:
"render": function (data, type, full, meta) {
return '<a href = "#(Url.Action("IndexPage", "Company"))/' + full[3] + '</a>';
You could use a delegated event handler to add the id to the link when it is clicked :
$("#data-table").on("click", "td:eq(0) a", function(e) {
this.href+=$(this).closest('tr').attr('id');
})
And forget about adding ROWID to the href in the render callback. The table is generated serverside and your Model.items is never passed to the client as data, so I cannot see any other workaround.

Categories

Resources