I would like to dynamically generate the columns definition on a Datatable. The columns definitions are:
"columns": [
{ "data": "id", "orderable": false },
{ "data": "code" },
{ "data": "name" },
{ "data": "created", "render":
function (data) {
var date = new Date(data);
return date.toLocaleString();
}
},
{ "data": "modified", "render":
function (data) {
var date = new Date(data);
return date.toLocaleString();
}
}]
I tried generating the javascript code using an array of php objects and then json_encode it, like the following:
$formatted_cols = [];
foreach ($cols as $idx => $col){
$temp = [];
$temp['data'] = $col;
if(in_array($col, array('id', 'actions'))){
$temp['orderable'] = 'false';
}
if(in_array($col, array('created', 'modified'))){
$temp['render'] = "
function (data) {
var date = new Date(data);
return date.toLocaleString();
}
";
}
$formatted_cols[] = $temp;
}
And then I do the following in the place where the code would normally appear:
echo json_encode($formatted_cols);
But the code came out like this:
[
{
"data": "id",
"orderable": "false"
},
{
"data": "code"
},
{
"data": "name"
},
{
"data": "created",
"render": "\r\n function (data) {\r\n var date
= new Date(data);\r\n \r\n return
date.toLocaleString();\r\n }\r\n "
},
{
"data": "modified",
"render": "\r\n function (data) {\r\n var date
= new Date(data);\r\n \r\n return date.toLocaleString();\r\n }\r\n "
}
]
As you can see, with a bunch of \r\n and stuff. Anybody can help me get the desired output please?
Thanks in advance for any help
UPDATE
I removed the line breaks but still the functions are inside double quotes
{
"data": "modified",
"render": "function (data) {var date = new Date(data);return
date.toLocaleString();}"
}
How do I remove those quotes?
Try using nl2br(). It'll take away all those \r and \n
http://php.net/manual/es/function.nl2br.php
The \r\n "stuff" represents a carriage-return + linefeed combination, in other words a line break.
You're going to get these in the JSON data if you're trying to encode multi-line strings. JSON itself does not support multi-line strings without them like PHP does.
Remove your newlines, like this:
{ "data": "created", "render": "function (data) { var date = new Date(data); return date.toLocaleString(); }" },
But you'll still be left with a string, which isn't the sort of thing you should work with, even though you can convert it to a function in JS. It's pretty ugly. Even if it worked, it's not great to generate JS in PHP - try to find another method if you can. Let PHP serve only the data, and have JS integrate functionality into it, if possible.
Related
I have a simple datatable that shows some JSON data, received from an API endpoint.
I added a column that will hold a button on each row of the table. This button, when hit, will fire an AJAX request with the value of id for that specific row.
This actual code works, but now, instead of only sending the value of id, i would also like to edit the table so that, when the button is hit, it will send the values of id and item for that row. Can someone give me some piece of advice on how to do that?
On another question, i've been told to use Data Attributes, but i don't really know how would i integrate this into my current code. Any advice is appreciated.
$(document).ready(function() {
$(document).on('click', '.btnClick', function() {
var statusVal = $(this).data("status");
console.log(statusVal)
callAJAX("/request_handler", {
"X-CSRFToken": getCookie("csrftoken")
}, parameters = {
'orderid': statusVal
}, 'post', function(data) {
console.log(data)
}, null, null);
return false;
});
let orderstable = $('#mytalbe').DataTable({
"ajax": "/myview",
"dataType": 'json',
"dataSrc": '',
"columns": [{
"data": "item"
}, {
"data": "price"
}, {
"data": "id"
},],
"columnDefs": [{
"targets": [2],
"searchable": false,
"orderable": false,
"render": function(data, type, full) {
return '<button type="button" class="btnClick sellbtn" data-status="replace">Submit</button>'.replace("replace", data);
}
}]
});
});
You could use the full parameter of the DataTables render function to store the values of the current seleceted row. In this way:
return '<button type="button" class="btnClick sellbtn" data-status="' + btoa(JSON.stringify(full)) + '">Submit</button>';
In the above code, the data-status data attribute will contains the stringified version of the current object value in base64 by using btoa(). In base64 because for some reason we cannot directly store the stringified version of the object in the button's data attribute.
Then, in the button's click event, you have to do:
Decode the stringified object by using atob().
Parse into object by using JSON.parse().
Something like this:
$(document).on('click', '.btnClick', function() {
var statusVal = $(this).data("status");
// Decode the stringified object.
statusVal = atob(statusVal);
// Parse into object.
statusVal = JSON.parse(statusVal);
// This object contains the data of the selected row through the button.
console.log(statusVal);
return false;
});
Then, when you click in the button you will see this:
So, now you can use this object to send in your callAJAX() function.
See in this example:
$(function() {
$(document).on('click', '.btnClick', function() {
var statusVal = $(this).data("status");
// Decode the stringified object.
statusVal = atob(statusVal);
// Parse into object.
statusVal = JSON.parse(statusVal);
// This object contains the data of the selected row through the button.
console.log(statusVal);
return false;
});
let dataSet = [{
"id": 1,
"item": "Item 1",
"price": 223.22
},
{
"id": 2,
"item": "Item 2",
"price": 243.22
},
{
"id": 3,
"item": "Item 3",
"price": 143.43
},
];
let orderstable = $('#myTable').DataTable({
"data": dataSet,
"columns": [{
"data": "item"
}, {
"data": "price"
}, {
"data": "id"
}, ],
"columnDefs": [{
"targets": [2],
"searchable": false,
"orderable": false,
"render": function(data, type, full) {
// Encode the stringified object into base64.
return '<button type="button" class="btnClick sellbtn" data-status="' + btoa(JSON.stringify(full)) + '">Submit</button>';
}
}]
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<link href="//cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet" />
<table id="myTable" class="display" width="100%"></table>
Hope this helps!
I've been try to send current page number to server by overwrite a variable called pgno
here is my code :
function fill_datatable(status='',pgno='')
{
var pgno = 0;
table = $('.tb_scoin_available').DataTable({
"processing": true,
"serverSide": true,
"ordering" : false,
"infoCallback": function( settings, start, end, max, total, pre ) {
var api = this.api();
var pageInfo = api.page.info();
pgno = pageInfo.page+1;
return pgno;
},
"ajax":{
"url": base_url+'/adminPath/management_scoin/ajaxGetScoinAvailable',
"type": "POST",
"data":{ _token: csrf_token, status : status,pgno : pgno}
},
"columnDefs": [ { orderable: false} ],
"columns": [
{ "data": "no" },
{ "data": "created_at" },
{ "data": "serial_scoin" },
{ "data": "unit_scoin" },
{ "data": "unit_scoin_desc" },
{ "data": "unit_scoin_sc" },
{ "data": "unit_scoin_idr" },
],
});
}
when I try to alert on infoCallback :
alert(pgno) the variable already overwrited, but when I try to dump the request on backend the pgno POST give me null result like this :
Anyone can help me out ?
You can get the table page with the page() function, no need for the whole "page.info". It's better explained in Datatable's API: https://datatables.net/reference/api/page()
The method you're trying to access is only to get the information, not to set it. That is probably why it isn't working. Check their docs for better understanding of their API: https://datatables.net/reference/api/page.info()
EDIT:
You can get the current page through a simple calculation. Since you're using serverSide processing, you already have start and length. You just need to do start/length + 1 and you will get the current page number.
I'm using Datatables and I'm trying to access data in another column. It's unclear to me if I should be using columns.data or if I should be taking another approach by using getting the column index instead?
Objective
In the second render function, I want the first makeSlug(data) to be referencing the "data": "district" and the second one to remain the same and reference "data": "school"
scripts.js
"columns": [
{ "data": "district",
"render": function (data, type, row, meta) {
return '' + data + '';
}
},
{ "data": "school",
"render": function (data, type, row, meta) {
return '' + data + '';
}
},
{ "data": "subject"},
{ "data": "rate"},
{ "data": "test_takers"}
],
Third argument row is an array containing full data set for the row. Use row['district'] to access district property.
For example:
{
"data": "school",
"render": function (data, type, row, meta) {
return '' + data + '';
}
}
My JSON data is:
[
{
"serviceName":"test",
"requestXML":"<soapenvelope><uname>testuser</uname></soapenvelope>"
},
{
"serviceName":"test2",
"requestXML":"<soapenvelope><uname>testuser2</uname></soapenvelope>"
}
]
jQuery code to call to backend which returns this JSON data
var postRequest = $.post(url);
postRequest.done(function( data ) {
$('#tableid').dataTable( {
"processing": true,
destroy: true,
"aaData": data,
"aoColumns": [
{ "data": "serviceName" },
{ "data": "requestXML" },
]
});
});
Now when it is shown on the screen as jQuery DataTable, I wanted the entire XML to be printed as it. But it just prints testuser instead of the whole XML.
Could anyone please help me with this as what is going wrong?
I have verified my JSON data is going correctly.
SOLUTION
You can use $('<div/>').text(data).html() trick to encode HTML entities.
For example:
$('#tableid').dataTable({
"processing": true,
"destroy": true,
"data": data,
"columns": [
{
"data": "serviceName"
},
{
"data": "requestXML",
"render": function(data, type, full, meta){
return $('<div/>').text(data).html();
}
}
]
});
DEMO
See this jsFiddle for code and demonstration.
Your server should take care of the response what it is sending. instead of sending
[
{"serviceName":"test","requestXML":"<soapenvelope><uname>testuser</uname></soapenvelope>"},
{"serviceName":"test2","requestXML":"<soapenvelope><uname>testuser2</uname></soapenvelope>"}
]
it should send something like below
[
{"serviceName":"test","requestXML":"<soapenvelope><uname>testuser</uname></soapenvelope>"},
{"serviceName":"test2","requestXML":"<soapenvelope><uname>testuser2</uname></soapenvelope>"}
]
If that is not possible ( you don't control the server ) then the following link should help
Escape markup in JSON-driven jQuery datatable?
First of all you will need XML escaping function (taken from here):
var XML_CHAR_MAP = {
'<': '<',
'>': '>',
'&': '&',
'"': '"',
"'": '''
}
function escapeXml (s) {
return s.replace(/[<>&"']/g, function (ch) {
return XML_CHAR_MAP[ch]
})
}
Then you can render cell content using it:
{
data: "requestXML",
render: function(data, method, object, pos) {
return '<pre>' + escapeXml(data) + '</pre>'
}
}
Now your XML should be visible. Remove pre tags, if not required.
I have a set of JSON data that are displayed using datatables. In one of the columns, I add a button and a text box only if the value in that column and another column meets a certain condition. this is the bit of code I used to do this:
$(document).ready(function (){
var alertTable = $('#alert-table').DataTable({
"jQueryUI": true,
"order": [ 3, 'desc' ],
"columns": [
{ "data": "source", "visible": false },
{ "data": "host" },
{ "data": "priority" },
{ "data": "ack", "render": function( data, type, row ) {
if (row.ack == "0" && row.priority > "2") {
return '<form><input class="ackname" type="text" value="Enter your name"><input class="ackbutton" type="button" value="Ack Alert" onclick="<get all items for that row and POST to a URL>"></form>';
}
return data;
}
},
],
"language": {
"emptyTable": "No Alerts Available in Table"
}
});
});
This works fine by adding a button and text in the cell. What I am looking to achieve is, when any of the button is been clicked, it should POST all the values for that row including what is typed in the text box to a URL which has another function that would extract those details and update the database and send back the refreshed data. I am new to datatables and jquery, any guide would be highly appreciated.
Have made some changes to the code, instead of form you can use div.
$(document).ready(function (){
var alertTable = $('#alert-table').DataTable({
"jQueryUI": true,
"order": [ 3, 'desc' ],
"columns": [
{ "data": "source", "visible": false },
{ "data": "host" },
{ "data": "priority" },
{ "data": "ack", "render": function( data, type, row ) {
if (row.ack == "0" && row.priority > "2") {
return '<div><input class="ackname" type="text" value="Enter your name"><input class="ackbutton" type="button" value="Ack Alert"></div>';
}
return data;
}
},
],
"language": {
"emptyTable": "No Alerts Available in Table"
}
});
$(document).on("click",".ackbutton",function() {
var currentIndex = $(this).parent().parent().index();
var rowData = alertTable.row( index ).data();
//extract the textbox value
var TextboxValue = $(this).siblings(".ackname").val();
var objToSave = {}; //Create the object as per the requirement
//Add the textbox value also to same object and send to server
objToSave["TextValue"] = TextboxValue;
$.ajax({
url: "url to another page"
data: JSON.stringify({dataForSave : objToSave}),
type: "POST",dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(datas) {
//Your success Code
},
error: function(error) {
alert(error.responseText);
}
});
});
});
Since both the pages are in same project, you can also do it using single ajax, passing all the values to server at once and then calling the other page internally from server and passing in the values using query string.
This is not a running code, rather to give you a basic idea on how to proceed.
Hope this helps :)