I am working on a report and it is very static. I was asked to change some of the numbers into a pie-chart or cool graph. So been looking at canvasjs but cannot figure it out.
The code I work with simple
<tr><td><?php echo __( 'Average Pagespeed', 'mainwp-pro-reports-extension' ); ?></td><td>[pagespeed.average.desktop] / 100</td></tr>
[/remove-if-empty]
The output is very basic
Average Pagespeed 39 / 100
I want to learn how to transform this into a pie-chart and spice it up a little. If just know how it fits together, I can figure this out for the other values I think.
Can someone guide me?
This is my attempt : I am new to coding as you can see
<tr><td><?php echo __( 'Average Pagespeed', 'mainwp-pro-reports-extension' ); ?></td><td>[pagespeed.average.desktop] / 100</td></tr>
<?php
$dataPoints = array(
array("label"=>"Speed", "y"=>[pagespeed.average.desktop]),
array("label"=>"Optimal", "y"=>100),
)
?>
<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function() {
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
title: {
text: "Page Speed"
},
subtitles: [{
text: "November 2017"
}],
data: [{
type: "pie",
yValueFormatString: "#,##0.00\"%\"",
indexLabel: "{label} ({y})",
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
[/remove-if-empty]
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>
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!
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>