Chart database data connection - php

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>

Related

PHP how to include a pie-chart

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]

How to search in a HTML table that does not generate any td's and such?

I've created a table based on the http://www.jtable.org template, my table, and most of the functionality is up and running, however I run into a problem when I want to include a search bar to filter tables results as I type. The problem I believe lies in the fact that most tables I've created using php have created the actual html table in the code so td's and tr's for example, and the search functionality would key off of matching these terms.
Currently however my table is being generated on the front end, without the actual HTML content in the back end, so I am unable to search. Is there any method I can use to search this table with this code, maybe using server side processing, or something else I'm unaware of?
This is the code I'm using:
<html>
<title> title </title>
<head>
<link href="themes/redmond/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" />
<link href="scripts/jtable/themes/metro/darkgray/jtable.css" rel="stylesheet" type="text/css" />
<script src="scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="scripts/jquery-ui-1.8.16.custom.min.js" type="text/javascript"></script>
<script src="scripts/jtable/jquery.jtable.js" type="text/javascript"></script>
</head>
<body>
<div class="filtering">
<body>
<input type="text" style="background-color: #e6ffff;" placeholder="Search Any Column" size="70" id="search";/>
</body>
<div id="PeopleTableContainer" style="width: relative;" ></div>
<img src="Sharks-2-Trans-30-150623-2.png" width="150" height="43" style="float:bottom-right; opacity: 10;">
<script type="text/javascript">
$(document).ready(function () {
//Prepare jTable
$('#PeopleTableContainer').jtable({
title: 'ICS Central',
paging: true, //Enable paging
pageSize: 10, //Set page size (default: 10)
sorting: true, //Enable sorting
defaultSorting: 'ISO_Name ASC', //Set default sorting
selecting: true, //Enable selecting
multiselect: true, //Allow multiple selecting
selectingCheckboxes: true, //Show checkboxes on first column
//selectOnRowClick: false, //Enable this to only select using checkboxes
actions: {
listAction: 'PersonActions2.php?action=list',
createAction: 'PersonActions2.php?action=create',
updateAction: 'PersonActions2.php?action=update',
deleteAction: 'PersonActions2.php?action=delete'
},
fields: {
PersonId: {
key: true,
create: false,
edit: false,
list: false
},
ISO_Name: {
title: 'ISO Name',
width: '5%'
},
ICS_Defect: {
title: 'Defect #',
width: '5%'
},
Abstract: {
title: 'Abstract',
width: '30%'
},
problem_description: {
title: 'Problem Description',
width: '30%'
},
fix_description: {
title: 'Fix Description',
width: '30%'
},
levels_approved: {
title: 'Levels Approved',
width: '30%'
},
reboot_required: {
title: 'Reboot Required?',
width: '30%'
},
reapplied_after_ccl: {
title: 'Reapplied After CCL?',
width: '30%'
},
reapplied_after_hmc_rebuild: {
title: 'Reapplied After HMC Rebuild?',
width: '30%'
},
bundle_fix_cmvc: {
title: 'Bundle Fix CMVC',
width: '30%'
}
},
//Register to selectionChanged event to hanlde events
selectionChanged: function () {
//Get all selected rows
var $selectedRows = $('#PeopleTableContainer').jtable('selectedRows');
$('#SelectedRowList').empty();
if ($selectedRows.length > 0) {
//Show selected rows
$selectedRows.each(function () {
var record = $(this).data('record');
$('#SelectedRowList').append(
'<b>ISO_Name</b>: ' + record.ISO_Name +
'<br /><b>Abstract</b>:' + record.Abstract + '<br /><br />'
);
});
} else {
//No rows selected
$('#SelectedRowList').append('No row selected! Select rows to see here...');
}
},
// rowInserted: function (event, data) {
// if (data.record.ISO_Name.indexOf('Add_Info_HB_v1.0.iso') >= 0) {
// $('#PeopleTableContainer').jtable('selectRows', data.row);
//}
//}
});
//Load student list from server
$('#PeopleTableContainer').jtable('load');
//Delete selected students
$('#DeleteAllButton').button().click(function () {
var $selectedRows = $('#PeopleTableContainer').jtable('selectedRows');
$('#PeopleTableContainer').jtable('deleteRows', $selectedRows);
});
});
</script>
</body>
</html>
I use a search text field and filter the result on keyUp, but that is not client side filtering. It makes the ajax call to the list action and uses a variable searchname to do its filtering. We use Hibernate and have a line of code that filters from the DB like: " obj.name like '%searchname%' "
<body>
<div class="filtering">
Name: <input type="text" id="search"/>
</div>
<body>
...
...
<script type="text/javascript">
$(document).ready(function () {
...
$('#search').keyup(function(){
$('#PeopleTableContainer').jtable('load', {searchname: $(this).val()});
});
}

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>

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}])';

Highcharts not displaying anything just blank html page

I tried to use the example given in highcharts website. But when i use it all i am getting is a blank html page. Someone please help me with the code. I do not understand why the code is not loading properly please tell me if i should add something extra to this, and please do let me know how to use a php array to make this graph work also
<html>
<head>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Browser market shares at a specific website, 2010'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
}
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: [
['Firefox', 45.0],
['IE', 26.8],
{
name: 'Chrome',
y: 12.8,
sliced: true,
selected: true
},
['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]
}]
});
});
});
</script>
</head>
<body>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
I believe your problem is in the order you included the scripts. Try placing jQuery first:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
Demo (working / not working).
Update: to load your data from MySQL using PHP, please see this example. However, as you pointed out yourself, encoding it using JSON might be a better option:
$data = array();
while($row = mysql_fetch_array($results)) {
$data[] = array($row[1], $row[0]);
}
echo json_encode($data);
This last echo can be used either to return the whole array using ajax (like the linked example above), or when generating the page itself (i.e. "hardcoding" it in the script):
series: [{
type: 'pie',
name: 'Browser share',
data: <?php echo json_encode($data)?>
}]
This will work since your array, when JSON encoded, can be used in place of a JavaScript literal (and the json_encode should take care of escaping everything, preventing XSS vulnerabilities).
The order of including javascripts should be:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
By this I mean, you have to include the jQuery library first before any other script.

Categories