append column data outside the datatable container - javascript

I am using JQuery datatable, after loading the data from server, my table looks something like this:
As you can see my table has six columns. The last column which is Contracted product, has the same data inside, I want to get the value and display it outside the datatable so it becomes more reader friendly as shown in picture 2.
My code looks like this:
var table = $('#products').DataTable( {
"processing": true,
"serverSide": true,
"paging": true,
"scrollX":"true",
"ordering": [],
"stateSave": false,
"info": true,
"dom": 'lrtip',
"ajax":
{
url:"xxxxxx_fetch.php",
type:'POST'
},
"columns": [
{ data: "product_code_fk" },
{ data: "product_name" },
{ data: "start_date" },
{ data: "end_date" },
{ data: "pack_size" },
{ data: "contract_prod" }
],
} );

Through the use of the header and footer callback manipulation functions provided by DataTables (headerCallback and footerCallback).
in HTML, by exemple
<tfoot>
<tr>
<th colspan="4" style="text-align:right">CONTRAT PROD :</th>
<th></th>
</tr>
</tfoot>
DataTable
$('#example').DataTable( {
"footerCallback": function ( row, data, start, end, display ) {
let api = this.api(), data;
...
$( api.column( 4 ).footer() ).html(
your_DATA
);

Related

Uncaught TypeError: data is undefined in Ajax call

My problem is I'm making an ajax sever-side call to retrieve an show information, I get a JSON that is an Object with an ArrayList of Objects inside, but when I try to make the call I get the table with a label saying Processing... all the time and this error in the browser log.
Does anyone knows why is this happening?
Here it's my HTML:
<table id="table_newsletterlist" class="display table">
<thead>
<tr>
<!-- Newsletters attributes -->
<th>Id</th>
<th>Asunto</th>
<th>Para</th>
</tr>
</thead>
<tfoot>
<tr>
<!-- Newsletters attributes -->
<td>Id</td>
<td>Asunto</td>
<td>Para</td>
</tr>
</tfoot>
</table>
Here my JS:
$('#table_newsletterlist').DataTable({
"processing": true,
"serverSide": true,
"ajax": newsletterUrl,
"columns": [
{
"data": "newsletters",
render: function (data){
return (data.id) ? data.id : "-";
}
},
{"data": "newsletters",
render: function (data){
return (data.target) ? data.target : "-";
}},
{"data": "newsletters",
render: function (data){
return (data.subject) ? data.subject : "-";
}},
]
});
And here the JSON I get:
{"total":188,"newsletters":[{"id":1,"subject":"Prueba","target":"groups","html":"<html>\r\n<head>\r\n\t<title></title>\r\n</head>\r\n<body>Probando</body>\r\n</html>\r\n","sender_id":1,"campaign_folder_id":null,"segment_id":null,"group_ids":[],"preview_text":null,"editor_type":"html","url_token":false,"analytics_utm_campaign":"","use_premailer":false}, {more objects like the first...}],"perPage":10,"page":1}
I made the following changes:
Because your JSON's row data array has the name newsletters, you need to refer to this name in the ajax section of your datatable: "dataSrc": "newsletters". This tells DataTables where to look in your JSON for the starting-point of its row iterator.
Following on from point 1, now you can refer to the specific fields in each array object, inside your columns section - for example: data: 'id'.
To simplify the use of - when there is no data, I recommend using defaultContent: "-". You can use a render function - but that is more complicated than you need here, for your specific example.
The end result is as follows:
$(document).ready(function() {
$('#table_newsletterlist')
.DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "http://localhost:7000/newsletters",
"type": "POST",
"dataSrc": "newsletters"
},
"columns": [{
data: 'id',
defaultContent: "-"
}, {
data: 'subject',
defaultContent: "-"
}, {
data: 'target',
defaultContent: "-"
}, {
data: 'preview_text',
defaultContent: "-"
}]
});
});

Datatable doesn't load JSON data, shows message "No data available in table"

I'm using Datatables.net to display data on my Shopify site. As an example, I just set the JSON data to have 1 key value pair of "itemcode" and then the actual product's item code. Here is an example of my data:
JSON Data
{
"jsonData": [
{
"itemcode": "0735340080 - Bearings"
},
{
"itemcode": "BL208-Z - Bearings"
},
{
"itemcode": "9109K - Bearings"
},
{
"itemcode": "735330016 - Bearings"
},
{
"itemcode": "699-ZZ - Bearings"
},
{
"itemcode": "698-ZZ - Bearings"
},
{
"itemcode": "697-ZZ - Bearings"
}
]
}
I'm using this code to load the data in. To clarify, the JSON is loaded from a hidden div element on the page:
Javascript Code
$(document).ready(function () {
var jsonDataDiv = document.getElementById("json-data").innerText;
var jsonData = JSON.parse(jsonDataDiv);
var table = $('#tableAppend').DataTable({
orderCellsTop: true,
pageLength: 25,
data: jsonData,
"columns": [{jsonData: "itemcode"}],
columnDefs: [
{"className": "dt-center", "targets": "_all"}
],
});
});
No errors are reported in the debug window, but my table states that no data was available. My HTML code is here:
HTML Code
<table class="display" id="tableAppend" style="margin-left: 20px;margin-right: 20px;">
<thead>
<tr>
<th class="dt-center">Item Code</th>
</tr>
</thead>
</table>
I've been following Q&A's online, but they don't seem to relate to my problem.
The issue is in the initialization of the table
Check out https://codepen.io/mvinayakam/pen/abzpJar
$(document).ready(function () {
var jsonDataDiv = document.getElementById("json-data").innerText;
var jsonData = JSON.parse(jsonDataDiv);
var table = $('#tableAppend').DataTable({
orderCellsTop: true,
pageLength: 25,
data: jsonData,
"columns": [{data: "itemcode"}],
columnDefs: [
{"className": "dt-center", "targets": "_all"}
],
});
})
As an aside, I am assuming the json is in the div only for trial purposes.
You have to only change the data table column assign parameter name jsonData --> data
"columns": [{data: "itemcode"}],

Getting a data from a page to another (specifically id) on my table using column render of datatables. Codeigniter

I would like to get the data of a specific row in my datatables and display it in another page where I edit the contents of the table. I have no idea how to do that. Here is my Javascript.
<script type="text/javascript">
var table;
$(document).ready(function() {
table = $('#table').DataTable({
"responsive": true,
"processing": true,
"serverSide": true,
"order": [],
"ajax": {
"url": "<?php echo site_url('Infoserbilis/ajax_list')?>",
"type": "POST"
},
"columnDefs": [{
"targets": [13], //first column / numbering column
"orderable": false,
"data": "download_link",
"render": function(data, type, full, meta) {
return 'Edit';
}, //set not orderable
}, ],
});
});
</script>

jquery data table and sorting columns

I'm using jquery data table to display large amounts of data inside grid. I implemented server side pagination but I'm struggling with sorting data server side.
Below is my datatable initialization, answer with query for sorting is not the subject here, I just need a way to pass information of which column is clicked to the controller, the one upon I will do the sorting.
('#myTable').dataTable({
"processing": true,
"serverSide": true,
"info": false,
"pageLength": 10,
"lengthChange": false,
"stateSave": false,
"bPaginate": true,
"bFilter": false,
"sPaginationType": "full_numbers",
"info": "Page _PAGE_ from _PAGES_",
"infoEmpty": "No data",
"oPaginate": {
"sFirst": "First",
"sPrevious": "Previous",
"sNext": "Next",
"sLast": "Last"
},
"ajax": {
"url": "#string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"))/MyController/GetData",
"type": "GET",
"data": function (d) {
.....
},
},
preDrawCallback: function (settings) {
...
},
drawCallback: function (settings) {
...
},
"columns": [
{ "data": "Id" },
{ "data": "FirstName" },
{ "data": "LastName" },
{ "data": "Age" }
],
"columnDefs": [
{
targets: [0],
orderable: false
},
{
render: function (data, type, row) {
...
}
],
"order": [[0, "desc"]]
});
public ActionResult GetData(){
var sortColumn = ...
...
}
You can bind the 'order' event like this:
$('#myTable').on( 'order.dt', function () {
var order = table.order();
var column_selected = order[0][0];
var order_way= order[0][1];
doStuff(column_selected ,order_way);
});
See it in plugin reference
By specifying "serverSide": true,, datatables will by default add information to the request which you need to use in your server-side code. If you look in the Firebug Network panel, you will be able to see the request with the querystring parameters. See here for the full list of parameters. Note that the link is to the v1.9 documentation, because that's what it looks like you're using.
So for sorting, you'd be interested in iSortCol_0 and sSortDir_0 which relate to the clicked column and the sort direction respectively.
In your controller method, you would access the parameters like this:
var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
var sortColumnDir = Request["sSortDir_0"];
You then need to incorporate this, and the other parameters into your query.
Here is an article on using server-side datatables with MVC

DataTables hyperlink on all rows in a column

I am using DataTables to generate a table. There is a column containing order numbers.
For example:
...
I need every row in this column to have a hyperlink to view/order?id=? where ? is the contents of row in the Order No column. For example the first row would be a hyperlink to view/order?id=1321755 etc.
What is the simplest way I can do so?
Here is the code that I am using to initialize the DataTables:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#example').dataTable( {
"serverSide": true,
"ajax": {
"url": "../server_processing/orders.php",
"type": "POST"
},
"order": [[ 0, "desc" ]]
} );
} );
</script>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Order No</th>
...
</tr>
</thead>
<tbody>
</tbody>
</table>
Check this out:
http://datatables.net/reference/option/columns.render
You can add a column render callback when you specify columns definition.
var columnsDef = [
...
{
"title": "Order No.",
"render": function (data, type, row, meta) {
return '' + data + '';
}
},
...
];
$("#table").dataTable({
...
"columns": columnsDef,
...
});
The data in that column will be changed to what the render function return.
I needed to use jQuery dataTables and turn a normal field to be a HREF field.
Here you have it all, including also dataTables error handling..
Enjoy..
Yosi Lev
1) The HTML part:
<!-- COMPANIES LIST start -->
<div id="compListDiv" style="visibility:hidden; position : absolute; left : 360px; top : 40px;">
<br>
<table id="compList" align="left" border="1">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>address</th>
</tr>
</thead>
</table>
</div>
<!-- COMPANIES LIST end -->
2) The javascript dataTables part:
When a button is clicked the following js function is called:
function companiesList(){
accountstable=$('#compList').dataTable({
sort : true,
bFilter: false,
bInfo: false,
paging:false,
autoWidth: true,
ajax: {
url: "http://localhost:8080/j112/rest-1/companies/list",
dataType: 'json',
dataSrc: "data",
error: function ( xhr, textStatus, error ) {
if ( textStatus === 'timeout' ) {
alert( 'Timout error. The server took too long to send back the data.\nPlease try again.' );
}
else {
alert( 'User Not In Session.' );
location.href = "login.html";
}
myDataTable.fnProcessingIndicator( false );
}//function
}/* ajax: */,
scrollCollapse: true,
bDestroy: true,
serverSide:true,
fnRowCallback : function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) { // this function is called for each row, but I could not use it to add the link
// if ( aData[1] == "A" )
//var td0 = $('td:eq(0)', nRow)[0];
// $('td:eq(0)', nRow).html( 'A');
// $('td:eq(0)', nRow).html( '<b>A</b>' )
},// fnRowCallback
initComplete : function(settings, json) { // this function is called after table is populated
//$("#compListDiv").show(); // this did not work so I used regular js to show the DIV
var d1 = document.getElementById('compListDiv');
d1.style.visibility = 'visible';
}, //initComplete
"columnDefs": [
{ "width": "10%", "targets": 0 },
{ "width": "20%", "targets": 0 },
{ "width": "70%", "targets": 0 }
],
"columns":[
//{"data" : "id"},
{ // render
"data": function (data, type, row, meta) {
return '' + data.id + '';
}
},
{"data" : "name"},
{"data" : "address"}
]
}); // dataTable()
}// companiesList()
By Yosi Lev - Feb 22, 2016

Categories

Resources