Populate DataTables Ajax Json object from PHP using multi tables - php
In my project I'm using DataTables to display my data, which is retrieved from an PHP echo json_encode. The PHP page is a script that returns JSON:
{
"sig1_re": [
{
"Ticket_RT": 716771,
"Cable_de_renvoi": 45,
"Longueur_de_ligne_(Selt)": 50,
"Res_LigneCoupee": "short",
"Ticket_fils": 152321,
"Numero_ND": "",
"Gamot_DateFermeture": "",
"Difference_de_date": "",
"Supprimer": "<a class='delete'><button>Delete</button></a>"
},
{
"Ticket_RT": 716760,
"Cable_de_renvoi": 45,
"Longueur_de_ligne_(Selt)": 67,
"Res_LigneCoupee": "open",
"Ticket_fils": "",
"Numero_ND": "",
"Gamot_DateFermeture": "",
"Difference_de_date": "",
"Supprimer": "<a class='delete'><button>Delete</button></a>"
}
],
"bad_nd": [
{
"Ticket_RT": 716620,
"Numero_ND": 236598741,
"Supprimer": "<a class='delete'><button>Delete</button></a>"
},
{
"Ticket_RT": 716577,
"Numero_ND": 565231583,
"Supprimer": "<a class='delete'><button>Delete</button></a>"
}
]
}
In my first attempt I had one JS file for each table in my HTLM and that works great, but I repeat the same code a lot and call the JSON echo each time, so I decided to regroup all my code in one JS file.
I managed to export almost all the tables options but I'm having trouble defining some variables; one is hideFromExport: I need to only copy the values from the first columns when I click on "COPY" button. The second problem is with oTable which I use to delete the row. I would like to set these two variables to be compatible with all my tables. (in my below example I use only two tables but in the actual project I have more).
Live Example: http://live.datatables.net/peceqofo/1/edit
Code:
<!DOCTYPE html>
<html>
<head>
<link href="https://raw.githubusercontent.com/twbs/bootstrap/master/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/responsive/2.1.0/css/responsive.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/buttons/1.2.2/css/buttons.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://raw.githubusercontent.com/FortAwesome/Font-Awesome/master/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<meta charset=utf-8 />
<title>DataTables - JS Bin</title>
</head>
<body>
<div class="container" style="width: 90%;">
<div class="panel panel-danger" style="margin: 5px;">
<div class="panel-heading">
<h2 class="panel-title">
<b>My Test</b>
</h2>
</div>
<div class="panel-body">
<div class="table-responsive">
<table id="tableA" class="table table-striped table-hover dt-responsive display nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>Ticket_RT</th>
<th>Cable_de_renvoi</th>
<th>Longueur_de_ligne_</th>
<th>Res_LigneCoupee</th>
<th>Ticket_fils RT</th>
<th>Gamot_DateFermeture</th>
<th>Numero_ND</th>
<th>Gamot_DateFermeture</th>
<th>Supprimer</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<br />
<table id="tableB" class="table table-striped table-hover dt-responsive display nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>Ticket_RT</th>
<th>Numero_ND</th>
<th>Supprimer</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.1.0/js/dataTables.responsive.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/dataTables.buttons.js"></script>
<script src="https://raw.githubusercontent.com/Stuk/jszip/master/dist/jszip.min.js"></script>
<script src="https://raw.githubusercontent.com/bpampuch/pdfmake/master/build/pdfmake.min.js"></script>
<script src="https://raw.githubusercontent.com/bpampuch/pdfmake/master/build/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.12/dataRender/ellipsis.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready( function () {
var jsonData = {};
$.ajax({
url: "http://www.json-generator.com/api/json/get/bUHEbjuIoi?indent=2",
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
console.log(jsonData);
var hideFromExport = [1, 2, 3]; /*<--- How i can custom this for each table individually ?? */
var options = {
responsive: true,
bAutoWidth: true,
dom: '<"top"lf>Bt<"bottom"pi><"clear">',
scrollY: 400,
scrollCollapse: true,
jQueryUI: true,
bProcessing: true,
sScrollX: "70%",
sScrollXInner: "100%",
bScrollCollapse: true,
bDestroy: true,
searching: false,
iDisplayLength: 25,
buttons: [{ /*<--- How i can custom this for each table individually ?? */
extend: 'copyHtml5',
exportOptions: {
columns: function(idx, data, node) {
var isVisible = table.column(idx).visible();
var isNotForExport = $.inArray(idx, hideFromExport) !== -1;
return isVisible && !isNotForExport ? true : false;
}
}
},
'excelHtml5', 'csvHtml5', 'pdfHtml5'
],
language: {
url: "https://cdn.datatables.net/plug-ins/1.10.12/i18n/French.json",
buttons: {
copy: 'Copier Tickets',
copyTitle: 'Ajouté au presse-papiers',
copyKeys: 'Appuyez sur <i>ctrl</i> ou <i>\u2318</i> + <i>C</i> pour copier les données du tableau à votre presse-papiers. <br><br>Pour annuler, cliquez sur ce message ou appuyez sur Echap.',
copySuccess: {
_: 'Copiés %d rangs',
1: 'Copié 1 rang'
}
}
}
};
function initialize(jsonData) {
/* --- TableA INIT --- */
options.aaData = jsonData.sig1_re;
options.aoColumns = [
{ "mData": "Ticket_RT" },
{ "mData": "Cable_de_renvoi" },
{ "mData": "Longueur_de_ligne_(Selt)" },
{ "mData": "Res_LigneCoupee" },
{ "mData": "Ticket_fils" },
{ "mData": "Gamot_DateFermeture" },
{ "mData": "Numero_ND" },
{ "mData": "Gamot_DateFermeture" },
{ "mData": "Supprimer" }
];
options.aoColumnDefs = [
{ "title": "Titre 1", "targets": 0 },
{ "title": "Titre 2", "targets": 1 },
{ "title": "Titre 3", "targets": 2 },
{ "title": "Titre 4", "targets": 3 },
{ "title": "Titre 5", "targets": 4 },
{ "title": "Titre 6", "targets": 5 },
{ "title": "Titre 7", "targets": 6 },
{ "title": "Titre 8", "targets": 7 },
{ "title": "Titre 9", "targets": 8 }
/*{ "targets": 1, "render": $.fn.DataTable.render.ellipsis(5) }*/
];
$("#tableA").dataTable(options);
/* --- TableB INIT --- */
options.aaData = jsonData.bad_nd;
options.aoColumns = [
{ "mData": "Ticket_RT" },
{ "mData": "Numero_ND" },
{ "mData": "Supprimer" }
];
options.aoColumnDefs = [
{ "title": "Titre 01", "targets": 0 },
{ "title": "Titre 02", "targets": 1 },
{ "title": "Titre 03", "targets": 2 },
{ "targets": 1, "render": $.fn.DataTable.render.ellipsis(5) }
];
$("#tableB").dataTable(options);
}
initialize(jsonData);
var oTable = $('#tableA').DataTable(); /*<--- How i can custom this for each table individually ?? */
$('#tableA').on('click', 'a.delete', function (e) {
oTable.row($(this).parents('tr')).remove().draw();
});
// Permet de réduire les commentaires et ajouter tooltip
$.fn.DataTable.render.ellipsis = function ( cutoff, wordbreak, escapeHtml ) {
var esc = function ( t ) {
return t
.replace( /&/g, '&' )
.replace( /</g, '<' )
.replace( />/g, '>' )
.replace( /"/g, '"' );
};
return function ( d, type, row ) {
// Order, search and type get the original data
if ( type !== 'display' ) {
return d;
}
if ( typeof d !== 'number' && typeof d !== 'string' ) {
return d;
}
d = d.toString(); // cast numbers
if ( d.length < cutoff ) {
return d;
}
var shortened = d.substr(0, cutoff-1);
// Find the last white space character in the string
if ( wordbreak ) {
shortened = shortened.replace(/\s([^\s]*)$/, '');
}
// Protect against uncontrolled HTML input
if ( escapeHtml ) {
shortened = esc( shortened );
}
return '<span class="ellipsis" title="'+esc(d)+'">'+shortened+'…</span>';
};
};
});
</script>
</body>
</html>
Solution :
Well after a lot of research i found an solution for the commun button options, now that works good ! Then I have added a button that will delete your selected row(s).
I hope this code will help more guys in the same situation like me !
Enjoy :)
Code :
<!DOCTYPE html>
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/responsive/2.1.0/css/responsive.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/buttons/1.2.2/css/buttons.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="css/bfm.css">
<meta charset=utf-8 />
<title>DataTables - JS Bin</title>
</head>
<body>
<div class="container" style="width: 90%;">
<div class="panel panel-danger" style="margin: 5px;">
<div class="panel-heading">
<h2 class="panel-title">
<b>My Test</b>
</h2>
</div>
<div class="panel-body">
<div class="table-responsive">
<table id="tableA" class="table table-striped table-hover dt-responsive display nowrap" cellspacing="0" width="100%"></table>
<br />
<table id="tableB" class="table table-striped table-hover dt-responsive display nowrap" cellspacing="0" width="100%"></table>
</div>
</div>
</div>
</div>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.1.0/js/dataTables.responsive.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/dataTables.buttons.js"></script>
<script src="https://raw.githubusercontent.com/Stuk/jszip/master/dist/jszip.min.js"></script>
<script src="https://raw.githubusercontent.com/bpampuch/pdfmake/master/build/pdfmake.min.js"></script>
<script src="https://raw.githubusercontent.com/bpampuch/pdfmake/master/build/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.12/dataRender/ellipsis.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready( function () {
var jsonData = {}; // get the json object array from php
$.ajax({
url: "http://www.json-generator.com/api/json/get/bTKebXDGdK?indent=2",
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
console.log(jsonData);
var buttonCommon = { // set default export column 0 (first column)
exportOptions: {
columns:[0]
}
};
var options = { // set options for tables
responsive: true,
bAutoWidth: true,
dom: '<"top"lf>Bt<"bottom"pi><"clear">',
scrollY: 400,
scrollCollapse: true,
jQueryUI: true,
bProcessing: true,
sScrollX: "70%",
sScrollXInner: "100%",
bScrollCollapse: true,
bDestroy: true,
searching: false,
iDisplayLength: 25,
buttons: [
$.extend( true, {}, buttonCommon, {
header: false,
extend: 'copyHtml5'
}),
'excelHtml5', 'csvHtml5', 'pdfHtml5',
{
text: 'Delete',
action: function ( e, dt, node, config ) { // function to delete selected rows on click button
dt.data().rows('.selected').remove().draw( false );
}
}
],
language: {
url: "json/French.json",
buttons: {
copy: 'Copy',
copyTitle: 'Ajouté au presse-papiers',
copyKeys: 'Appuyez sur <i>ctrl</i> ou <i>\u2318</i> + <i>C</i> pour copier les données du tableau à votre presse-papiers. <br><br>Pour annuler, cliquez sur ce message ou appuyez sur Echap.',
copySuccess: {
_: 'Copiés %d rangs',
1: 'Copié 1 rang'
}
}
}
};
function initialize(jsonData) {
/* --- TableA INIT --- */
options.aaData = jsonData.sig1_re;
options.aoColumns = [
{ "mData": "Ticket_RT" },
{ "mData": "Cable_de_renvoi" },
{ "mData": "Longueur_de_ligne_(Selt)" },
{ "mData": "Res_LigneCoupee" },
{ "mData": "Ticket_fils" },
{ "mData": "Gamot_DateFermeture" },
{ "mData": "Numero_ND" },
{ "mData": "Difference_de_date" }
];
options.aoColumnDefs = [
{ "title": "Titre 1", "targets": 0 },
{ "title": "Titre 2", "targets": 1 },
{ "title": "Titre 3", "targets": 2 },
{ "title": "Titre 4", "targets": 3 },
{ "title": "Titre 5", "targets": 4 },
{ "title": "Titre 6", "targets": 5 },
{ "title": "Titre 7", "targets": 6 },
{ "title": "Titre 8", "targets": 7 }
/*{ "targets": 1, "render": $.fn.DataTable.render.ellipsis(5) }*/
];
$("#tableA").dataTable(options);
/* --- TableB INIT --- */
options.aaData = jsonData.bad_nd;
options.aoColumns = [
{ "mData": "Ticket_RT" },
{ "mData": "Numero_ND" }
];
options.aoColumnDefs = [
{ "title": "Titre 01", "targets": 0 },
{ "title": "Titre 02", "targets": 1 },
{ "targets": 1, "render": $.fn.DataTable.render.ellipsis(5) } // call function to render + tooltip
];
$("#tableB").dataTable(options);
}
initialize(jsonData);
$('#tableA tbody').on( 'click', 'tr', function () { // set multi select rows
$(this).toggleClass('selected');
});
$('#tableB tbody').on( 'click', 'tr', function () { // set multi select rows
$(this).toggleClass('selected');
});
// Function to delimit render + tootil
$.fn.DataTable.render.ellipsis = function ( cutoff, wordbreak, escapeHtml ) {
var esc = function ( t ) {
return t
.replace( /&/g, '&' )
.replace( /</g, '<' )
.replace( />/g, '>' )
.replace( /"/g, '"' );
};
return function ( d, type, row ) {
// Order, search and type get the original data
if ( type !== 'display' ) {
return d;
}
if ( typeof d !== 'number' && typeof d !== 'string' ) {
return d;
}
d = d.toString(); // cast numbers
if ( d.length < cutoff ) {
return d;
}
var shortened = d.substr(0, cutoff-1);
// Find the last white space character in the string
if ( wordbreak ) {
shortened = shortened.replace(/\s([^\s]*)$/, '');
}
// Protect against uncontrolled HTML input
if ( escapeHtml ) {
shortened = esc( shortened );
}
return '<span class="ellipsis" title="'+esc(d)+'">'+shortened+'…</span>';
};
};
});
</script>
</body>
</html>
I would suggest to keep the tables separate with attributes. And if you would like to add extra columns and buttons in data tables. You can achieve that using following approach.
Add an extra column for action.
On fnRowCallback method add specific class to the action column.
Example of click on action:
jQuery('#datatable tbody').on('click', 'td.action', function () {
//call custom method to format the data inside td.action column.
data = {
'id': $(this).attr('cour_id')
};
tr.after(format(data)).show();
});
It will create action button for each row with specific row ids and attributes and won't conflict with each other.
Hope it will help!
Related
Chart database data connection
I have problem with connecting my mysql database to Highstock chart Here is my code - it does not show anything when I run it shows just empty page Can someone tell me what I am doing wrong or send me example for the script with database connection? I would really appreciate <!DOCTYPE HTML> <html> <body> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script src="../../code/highstock.js"></script> <script src="../../code/modules/exporting.js"></script> <div id="container" style="height: 400px; min-width: 310px"></div> <script type="text/javascript"> <?php $conn=mysqli_connect("localhost:3307","sampleuser","samplepass","sampledatabase"); if(!$conn) { die("connection in error:".mysqli_connect_error()); } $result=mysqli_query($conn,"Select time,open,close,high,low,volume From sampletable "); while ($row = mysql_fetch_array($result)) { extract $row; $time *= 1000; // convert from Unix timestamp to JavaScript time $data[] = "[$time,$open,$close,$high,$low,$volume]"; } ?> Highcharts.stockChart('container', { title: { text: 'AAPL stock price by minute' }, rangeSelector: { buttons: [{ type: 'hour', count: 1, text: '1h' }, { type: 'day', count: 1, text: '1D' }, { type: 'all', count: 1, text: 'All' }], selected: 1, inputEnabled: false }, series: [{ name: 'AAPL', type: 'candlestick', data: data, tooltip: { valueDecimals: 2 } }] }); </script> </body> </html>
load php/mysql data to amcharts using dataloader
I am new to AmCharts and having trouble to display the simple graph that I needed. I have used codes from the AmCharts live editor. This is the PHP file (getGred.php) $query = "SELECT gred, COUNT( gred ) AS bilangan FROM borg_peribadi GROUP BY gred"; $result = mysql_query( $query ); //echo $query; //echo "<br>"; $rows = array(); while ($data = mysql_fetch_assoc ($result)){ $rows[] = array( "gred" => $data[ 'gred' ], "bilangan" => $data[ 'bilangan' ] ); } echo json_encode( $rows ); And this is what I got from AmCharts tutorial: <!DOCTYPE html> <html> <head> <title>Laporan eOrientasi</title> <meta name="description" content="chart created using amCharts live editor" /> <!-- amCharts javascript sources --> <script src="../amcharts/amcharts.js" type="text/javascript"></script> <script src="../amcharts/serial.js" type="text/javascript"></script> <!-- amCharts plugins --> <script src="https://www.amcharts.com/lib/3/plugins/export/export.min.js type="text/javascript""></script> <link rel="stylesheet" href="https://www.amcharts.com/lib/3/plugins/export/export.css"> <script src="../amcharts/plugins/dataloader/dataloader.min.js" type="text/javascript"></script> <!-- amCharts javascript code --> <script type="text/javascript"> AmCharts.makeChart("chartdiv", { "type": "serial", "dataLoader": { "url": "getGred.php", "format": "json" }, "categoryField": "gred", "angle": 30, "depth3D": 30, "startDuration": 1, "export": { "enabled": true }, "categoryAxis": { "gridPosition": "start" }, "chartCursor": { "enabled": true }, "chartScrollbar": { "enabled": true }, "trendLines": [], "graphs": [ { "balloonText": "[[title]] of [[category]]:[[value]]", "fillAlphas": 1, "id": "AmGraph-1", "title": "bil. pegawai", "type": "column", "valueField": "bilangan" } ], "guides": [], "valueAxes": [ { "id": "ValueAxis-1", "title": "Bilangan" } ], "allLabels": [], "balloon": {}, "legend": { "enabled": true, "useGraphSettings": true }, "titles": [ { "id": "Title-1", "size": 15, "text": "BIL PEGAWAI MELAPOR DIRI MENGIKUT GRED" } ], // "dataProvider": AmCharts.loadJSON('laporan/getGred.php') } ); </script> </head> <body> <div id="chartdiv" style="width: 100%; height: 400px; background-color: #FFFFFF;" ></div> </body> </html> The problem is not the graph is not showing, only displays below:output Hope to get some pointers on any of errors or mistakes. Thank you. edit: i've added the output from getGred.php [{"gred":"29","bilangan":"1"},{"gred":"41","bilangan":"5"},{"gred":"44","bilangan":"6"}]
How to show pictures in a table using jQuery DataTables
Is that possible that I can show my URL images in data-table? I returning my data in array as it shown here in my code and returning the URL image with... Before I knew the DataTables I was using the default table an put my table in <img src=""> so how can I use it here? <?php class basket_report{ function show_basket_report(){ $connect_mysql= #mysql_connect($server,$username,$passwor) or die ("Connection Failed!"); $mysql_db=mysql_select_db("GP15",$connect_mysql) or die ("Could not Connect to Database"); $query = "SELECT * FROM reportBasket where notifyEmployee='1'"; $result=mysql_query($query) or die("Query Failed : ".mysql_error()); $objects= array(); while($rows=mysql_fetch_array($result)) { $objects[]= $rows; } $data_set = "["; $count_rows = count($objects); $count = 1; foreach($objects as $object){ $data_set .= "['". $object['reportID'] ."', '". $object['email'] ."', '". $object['date'] ."', '". $object['time'] ."', '". $object['BasketID'] ."', '". $object['notifyEmployee'] ."','". $object['replyedPhoto'] ."']"; if($count != $count_rows){ $data_set .= ","; $count++; } } $data_set .= "]"; return $data_set; } ?> <html> <head> <script src="js/jquery-1.11.1.js"></script> <!-- DataTables CSS --> <link rel="stylesheet" type="text/css" href="DataTables-1.10.7/media/css/jquery.dataTables.css"> <!-- jQuery --> <script type="text/javascript" charset="utf8" src="DataTables-1.10.7/media/js/jquery.js"></script> <!-- DataTables --> <script type="text/javascript" charset="utf8" src="DataTables-1.10.7/media/js/jquery.dataTables.js"></script> <script> $(document).ready(function() { $('#table_id').dataTable( { "data": dataSet, "columns": [ { "title": "report_id" }, { "title": "email" }, { "title": "date" }, { "title": "time"}, { "title": "basket_id"}, { "title": "notify_Employee"}, { "title": "replyed_photo"} ] } ); } ); </script> </head> <body> <table id="table_id" class="display"> </table> <?php include('class_report_basket.php'); $basket_report = new basket_report(); ?> <script> var dataSet= <?php echo $basket_report->show_basket_report(); ?>; </script> </body> </html>
You can use columns.render option to define callback function to render cell content based on its data. $('#example').DataTable({ "ajax": { url: "/test/0", }, "columns": [ { "data": 0 }, { "data": 1, "orderable": false, "sortable": false, "render": function (data, type, row, meta){ // If data will be displayed if(type === "display"){ return '<img src="' + data + '">'; // Otherwise, if search/filtering is performed } else { return data; } } } ] }); 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 which to specify any options). Alternatively, you can use columnDefs to target specific columns. See the example below for code and demonstration. Please note, that I'm using jQuery Mockjax plug-in just for the sake of demonstrating Ajax request, it's not needed for production code. $(document).ready(function () { // AJAX emulation for demonstration only $.mockjax({ url: '/test/0', responseTime: 200, responseText: { "data": [ [ "100x150", "http://placehold.it/100x150" ], [ "200x150", "http://placehold.it/200x150" ], [ "300x150", "http://placehold.it/300x150" ] ] } }); $('#example').DataTable({ "ajax": { url: "/test/0", }, "columns": [ { "data": 0 }, { "data": 1, "orderable": false, "sortable": false, "render": function (data, type, row, meta){ if(type === "display"){ return '<img src="' + data + '">'; } else { return data; } } } ] }); }); <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script> <script src="http://vitalets.github.com/x-editable/assets/mockjax/jquery.mockjax.js"></script> </head> <body> <table id="example" class="display" cellspacing="0" width="100%"> <thead> <tr> <th>Name</th> <th>Picture</th> </tr> </thead> </table> </body> </html>
Highlight cell data in datatables
I'm trying to highlight data in green that is showing positive growth or vice versa. But i'm facing some issues in Chrome browser while it works fine in Firefox. Please help me. $(document).ready(function() { $('#example').dataTable( { "ordering": false, "columnDefs": [ { "targets": 4, "createdCell": function (td, cellData, rowData, row, col) { if ( cellData.contains("-")) // works fine for Firefox but not for Chrome $(td).css('color', 'red') else $(td).css('color', 'green') } }, { "render": function ( data, type, row ) { return data +' ('+ Math.round(row[4]*10)/10+'%)'; },"targets": 3 } ] }); } ); </script> <script src="//code.jquery.com/jquery-1.11.0.min.js"></script> <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script> <!-- DataTables CSS --> <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.0/css/jquery.dataTables.css"> <!-- DataTables --> <script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.0/js/jquery.dataTables.js"></script> <!--DATATABLES--> <script src="//code.jquery.com/jquery-1.10.2.min.js"></script> <script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script> <script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.0/js/jquery.dataTables.js"></script> <table id="example" class="display" cellspacing="0" width="100%"> <thead> <tr> <th>Metrics</th> <th>Till Now</th> <th>Today Trending</th> <th>Yesterday</th> <th>DY</th> <th>5 Day Average</th> <th>Same Time Last <?php echo date("l");?></th> <th>Highest</th> <th>Lowest</th> <th>Target</th> <th>Run Rate</th> </tr> </thead> <tfoot> <tr> <th>Metrics</th> <th>Till Now</th> <th>Today Trending</th> <th>Yesterday</th> <th>DY</th> <th>5 Day Average</th> <th>Same Time Last <?php echo date("l");?></th> <th>Highest</th> <th>Lowest</th> <th>Target</th> <th>Run Rate</th> </tr> </tfoot> <tbody> <?php while($row = $statement->fetch(PDO::FETCH_ASSOC)){ echo '<tr>'; echo '<td>'.'<strong>'.$row['metric'].'</strong>'.'</td>'; //Till Now echo '<td>'.number_format($row['Till_Now'], 2, '.', '').'</td>'; //Trending echo '<td>'.number_format($row['Trending'], 2, '.', '').'</td>'; //Yesterday echo '<td>'.number_format($row['Yesterday'],2,'.','').'</td>'; //Diff echo '<td>'.($row['Trending']-$row['Yesterday'])*100/$row['Yesterday'].'</td>'; //5_days_avg echo '<td>'.number_format($row['5_days_avg'],2,'.','').'</td>'; //STLW echo '<td>'.number_format($row['stlw'],2,'.','').'</td>'; ?> Any help will be appreciated. Thanks in advance!
you will need to edit the css and program it for chrome. have you tried it? edit: try double quote marks " where the colors go.
This worked for me, hope it helps : <script type="text/javascript"> $(document).ready(function() { $('#example').dataTable( { "ordering": false, "columnDefs": [ //Shortening data cell { "render": function ( data, type, row ) { return data +' ('+ Math.round(row[4]*10)/10+'%)'; },"targets": 3 }, //Hide column { "visible": false, "targets": [ 4 ] }, //Highlighting data { "targets": [3], "createdCell": function (td, cellData, rowData, row, col){ if ( cellData.indexOf("-")==-1) $(td).css('color', 'green') else $(td).css('color', 'red') } } ] }); } );
This code syntax usually works in Google Chrome: $('.status:contains("Paid")').css('color', 'red'); $('.status:contains("Received")').css('color', 'green');
JSONP response for Kendo UI does not populate grid
Please give me your advice. The following URL gives jsonp formatted data: http://demos.kendoui.com/service/Products However, only change I made was use my own url pointing to simple php to get jsonp data as below: <?php header('Vary: Accept-Encoding'); header('Connection: Keep-Alive'); header('Content-Encoding: gzip'); header('Content-Length: 1743'); header('Content-Type: application/x-javascript; charset=utf-8'); echo gzencode('callback([{"ProductID":2,"ProductName":"Chang","UnitPrice":19,"UnitsInStock":17,"Discontinued":false}])'); ?> The HTML source is below: <!DOCTYPE html><html><head> <title>ESS Software Inventory</title> <meta charset="utf-8"> <link href="./kendoui/content/shared/styles/examples-offline.css" rel="stylesheet"> <link href="./kendoui/styles/kendo.common.min.css" rel="stylesheet"> <link href="./kendoui/styles/kendo.rtl.min.css" rel="stylesheet"> <link href="./kendoui/styles/kendo.default.min.css" rel="stylesheet"> <script src="./kendoui/js/jquery.min.js"></script> <script src="./kendoui/js/kendo.web.min.js"></script> <script src="./kendoui/content/shared/js/console.js"></script> <script> </script> </head><body> <a class="offline-button" href="../index.html">Back</a> <div id="example" class="k-content"> <div id="grid"></div> <script> $(document).ready(function () { var crudServiceBaseUrl = "http://dnettools/essinventory/cgi-bin", //var crudServiceBaseUrl = "http://demos.kendoui.com/service", dataSource = new kendo.data.DataSource({ transport: { read: { url: crudServiceBaseUrl + "/products.php", //url: crudServiceBaseUrl + "/Products", dataType: "jsonp" }, update: { url: crudServiceBaseUrl + "/products.php", dataType: "jsonp" }, destroy: { url: crudServiceBaseUrl + "/products.php", dataType: "jsonp" }, create: { url: crudServiceBaseUrl + "/products.php", dataType: "jsonp" }, parameterMap: function(options, operation) { if (operation !== "read" && options.models) { return {models: kendo.stringify(options.models)}; } } }, batch: true, pageSize: 20, schema: { model: { id: "ProductID", fields: { ProductID: { editable: false, nullable: true }, ProductName: { validation: { required: true } }, UnitPrice: { type: "number", validation: { required: true, min: 1} }, Discontinued: { type: "boolean" }, UnitsInStock: { type: "number", validation: { min: 0, required: true } } } } } }); $("#grid").kendoGrid({ dataSource: dataSource, navigatable: true, pageable: true, height: 430, toolbar: ["create", "save", "cancel"], columns: [ "ProductName", { field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: 110 }, { field: "UnitsInStock", title: "Units In Stock", width: 110 }, { field: "Discontinued", width: 110 }, { command: "destroy", title: " ", width: 90 }], editable: true }); }); </script> </div> </body></html>
had to use this: since the returned jsonp should have dynamic callback name parse_str($_SERVER['QUERY_STRING']); <br/> echo "$callback" . '([{"ProductID":1,"ProductName":"Chai","UnitPrice":18,"UnitsInStock":39,"Discontinued":false},{"ProductID":2,"ProductName":"Chang","UnitPrice":19,"UnitsInStock":17,"Discontinued":false},{"ProductID":3,"ProductName":"Aniseed Syrup","UnitPrice":10,"UnitsInStock":13,"Discontinued":false},{"ProductID":4,"ProductName":"Chef Anton\u0027s Cajun Seasoning","UnitPrice":22,"UnitsInStock":53,"Discontinued":false}])';