I am trying to make a web app using PHP & AJAX. It should retrieve data from Elasticsearch without refreshing the page(live search). Is it possible to implement such retrieval on elasticsearch index?
For that, I have made these two files:
index2.php
<?php
session_start();
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax-Trials</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<br />
<h2 align="center">Ajax Live Data Search using Jquery, PHP, Elasticsearch</h2><br />
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Search</span>
<input type="text" name="search_text" id="search_text" placeholder="Search by Customer Details" class="form-control" />
</div>
</div>
<br />
<div id="result"></div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch2.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
and here is fetch2.php
<?php
session_start();
require_once '../vendor/autoload.php';
use Elasticsearch\ClientBuilder;
$client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
$output = '';
if(isset($_POST["query"]))
{
$search = $_POST["query"];
$query = $client->search([
'body' => [
'query' => [
'bool' => [
'should' => [
'multi_match' => [
"fuzziness" => "AUTO",
'fields' => ['district','countrycode','name','population'],
'query' => $search
]
]
]
],
'from' => 0,
'size' => 100
]
]);
if($query['hits']['total']>=1){
$results = $query['hits']['hits'];
}
}
if(isset($results))
{
$output .= '
<div class="table-responsive">
<table class="table table bordered">
<tr>
<th>ID</th>
<th>Name</th>
<th>CountryCode</th>
<th>District</th>
<th>Population</th>
</tr>
';
foreach($results as $r)
{
$output .= '
<tr>
<td>'.$r['_id'].'</td>
<td>'.$r['_source']['name'].'</td>
<td>'.$r['_source']['countrycode'].'</td>
<td>'.$r['_source']['district'].'</td>
<td>'.$r['_source']['population'].'</td>
</tr>
';
}
echo $output;
}
else
{
echo 'Data Not Found';
}
?>
When I search for any string, It successfully prints the Headers of the table but is not printing a data. What is the issue here?
The JSON format of the index is this:
{
"_index": "cities",
"_type": "city",
"_id": "35",
"_version": 1,
"_score": 0,
"_source": {
"id": 35,
"#timestamp": "2020-03-10T18:24:46.963Z",
"#version": "1",
"population": 2168000,
"district": "Alger",
"countrycode": "DZA",
"name": "Alger"
},
"fields": {
"#timestamp": [
"2020-03-10T18:24:46.963Z"
]
}
}
Your JSON format shows the data returned is an object.
To access object values code the following:
foreach($results as $r)
{
$output .= '
<tr>
<td>'.$r->_id.'</td>
<td>'.$r->_source->name.'</td>
<td>'.$r->_source->countrycode.'</td>
<td>'.$r->_source->district.'</td>
<td>'.$r->_source->population.'</td>
</tr>
';
}
As you can see I used -> (Object) instead of [] (array)
I just removed the 'population' field from the search fields and it worked. Elasticsearch here could not search numeric input and from a numerical field.
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>
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"}]
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!
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');