I want to draw one page with HighChart. I took data from database. I wrote it with json_encode. I can see what my $xxx has value. Its json format. But my graph is not working. I think var data = <?php echo json_encode($xxx); ?> doesnt work and return valur. Where do I mistake?
Here is my php code for database value:
<?php
$var = "SELECT SUBSTRING(KayitTarihi,1,4) AS year,SUBSTRING(KayitTarihi,6,2) AS month,SUBSTRING(KayitTarihi,9,2) AS day,SUBSTRING(KayitTarihi,12,2) AS saat,SUBSTRING(KayitTarihi,15,2) AS dakika,Guc FROM Urun WHERE Date(KayitTarihi)=\"".$link_m."\"";
$result = $mysqli->query($var);
$data = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
$no = 1;
$total_deger=count($data);
foreach($data as $dat)
{
$xxx ="[Date.UTC(".$dat['year'].",".$dat['month'].",".$dat['day'].",".$dat['saat'].",".$dat['dakika'].",00),".$dat['Guc']."]";
if($no < $total_deger)
{
echo ",";
}
echo json_encode($xxx);
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
?>
And here is my highchart script:
<script>
$(function () {
var data = <?php echo $xxx; ?>;
Highcharts.chart('container', {
chart: {
zoomType: 'x'
},
title: {
text: 'USD to EUR exchange rate over time'
},
subtitle: {
text: document.ontouchstart === undefined ?
'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in'
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Exchange rate'
}
},
legend: {
enabled: false
},
plotOptions: {
area: {
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, Highcharts.getOptions().colors[0]],
[1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
]
},
marker: {
radius: 2
},
lineWidth: 1,
states: {
hover: {
lineWidth: 1
}
},
threshold: null
}
},
series: [{
type: 'area',
name: 'USD to EUR',
data: [data]
}]
});
});
</script>
Edit: I edited json format. When I write just echo. Its just see one value.
Edit2: I have 9 value. My output is:
,,,,,,,,[Date.UTC(2016,11,15,10,28,00),0]
[Date.UTC(2016,11,15,14,25,00),0]
[Date.UTC(2016,11,15,14,25,00),0]
[Date.UTC(2016,11,15,14,27,00),17]
[Date.UTC(2016,11,15,18,32,00),54]
[Date.UTC(2016,11,15,18,32,00),54]
[Date.UTC(2016,11,15,18,33,00),93]
[Date.UTC(2016,11,15,18,33,00),34]
[Date.UTC(2016,11,15,18,34,00),34]
But when ı read docs for highchart my value must be
([
[Date.UTC(2016,11,15,10,28,00),0],
[Date.UTC(2016,11,15,14,25,00),0],
[Date.UTC(2016,11,15,14,25,00),0],
[Date.UTC(2016,11,15,14,27,00),17],
[Date.UTC(2016,11,15,18,32,00),54],
[Date.UTC(2016,11,15,18,32,00),54],
[Date.UTC(2016,11,15,18,33,00),93],
[Date.UTC(2016,11,15,18,33,00),34],
[Date.UTC(2016,11,15,18,34,00),34]
]);
Try wrapping it in quotes
var data = "<?php echo json_encode($xxx); ?>"
You should see this as an error in the console
Also you arent concatenating correctly. This means every time the loop runs you are overwriting the last entry stored in $xxx
$xxx = "[Date.UTC(".$dat['year'].",".$dat['month'].",".$dat['day'].",".$dat['saat'].",".$dat['dakika'].",00),".$dat['Guc']."]";
should be
$xxx .= "[Date.UTC(".$dat['year'].",".$dat['month'].",".$dat['day'].",".$dat['saat'].",".$dat['dakika'].",00),".$dat['Guc']."]";
Finally, change your loop to work like this
$xxx = '';
foreach($data as $dat){
// if not a blank string i.e. something added, add a comma to the end read for the next concatenation
if($xxx != '') $xxx .= ",";
// concatenate
$xxx .= "[Date.UTC(".$dat['year'].",".$dat['month'].",".$dat['day'].",".$dat['saat'].",".$dat['dakika'].",00),".$dat['Guc']."]";
}
// if not blank string, echo
if($xxx != ''){
echo json_encode($xxx);
}
Related
I just learned about creating dynamic charts using highcharts. I need help, i'm trying to make a dynamic spline chart with data from php like this (number 2). Then I try to create a dynamic spline chart under it (different div) by varying the data in php. But the results only show the chart below (chart B), on chart A does not display data as before B chart added. I asked, how to make two dynamic spline charts on one page? thank you
This is the code that I use
<?php //PHP for Chart A
// Set the JSON header
header("Content-type: text/json");
// The x value is the current JavaScript time, which is the Unix time multiplied
// by 1000.
$x = time() * 1000;
// The y value is a random number
$y = rand(0, 100);
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>
<?php //PHP for Chart B
// Set the JSON header
header("Content-type: text/json");
// The x value is the current JavaScript time, which is the Unix time multiplied
// by 1000.
$x = time() * 1000;
// The y value is a random number
$y = rand(100, 200);
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>
this is javascript code:
//JS of Chart A
var chart;
function requestData() {
$.ajax({
url: 'dataChartA.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
document.addEventListener('DOMContentLoaded', function() {
chart = Highcharts.chart('chartA', {
chart: {
type: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Chart A'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Chart A',
data: []
}]
});
});
//JS for Chart B
var chart;
function requestData() {
$.ajax({
url: 'dataChartB.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
document.addEventListener('DOMContentLoaded', function() {
chart = Highcharts.chart('chartB', {
chart: {
type: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Chart B'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value B',
margin: 80
}
},
series: [{
name: 'Chart B',
data: []
}]
});
});
</head>
<body>
<div id="chartA"></div>
<div id="chartB"></div>
</body>
Results in the browser : https://imgur.com/kAVGQUk
I want to show data recieved from MySQL in Highchart.js graphic. For that, I'm using two textboxes which being entered to date informations. Finally, using a single button which calls function (chart.php). By the way, I'm getting date informations and sending to mysql.php with $.post method in the function. Then I want to get MySQL datas to show in Highchart.js. But program is giving me empty array. Actually, array have a lot of datas, because function(data) is showing datas in the ($.post).
chart.php
function zaman_al()
{
var baslangic=document.getElementById('rest_example_3').value;
var son=document.getElementById('rest_example_4').value;
if (baslangic=="" || son=="")
{
alert("Lütfen Tarih bilgisi Giriniz !!!");
}
else
{
baslangic = new Date(baslangic);
baslangic = baslangic.getTime();
son = new Date(son);
son= son.getTime();
if (son<=baslangic)
{
alert("Geçersiz Tarih Girişi !!!");
}
if (son>baslangic)
{
var veri={'baslama':(baslangic/1000),'bitirme':(son/1000)};
$.post('mysql.php',veri,
function(data)
{
alert(data);
$(function () {
$('#kku').highcharts({
chart: {
type: 'spline'
},
title: {
text: 'Snow depth at Vikjafjellet, Norway'
},
subtitle: {
text: 'Irregular time data in Highcharts JS'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
},
title: {
text: 'Date'
}
},
yAxis: {
title: {
text: 'Snow depth (m)'
},
min: 0
},
tooltip: {
headerFormat: '<b>{series.name}</b><br>',
pointFormat: '{point.x:%e. %b}: {point.y:.2f} m'
},
plotOptions: {
spline: {
marker: {
enabled: true
}
}
},
series: [{
name: 'Winter 2007-2008',
// Define the data points. All series have a dummy year
// of 1970/71 in order to be compared on the same x axis. Note
// that in JavaScript, months start at 0 for January, 1 for February etc.
data: [
<?php
$veri=explode('"',$sonuc);
for ($i = 0; $i < count($veri); $i++)
{
if(($i%4)==1)
{
echo "[".$veri[$i].","; // time
}
if(($i%4)==3)
{
echo $veri[$i]."],\n"; // sensor_value
}
};
?>
]
}]
});
});
});
}
}
}
Above code for button function. By the way.
chart.php
<b>Başlangıç Zamanı :</b> </td>
<td><input style="border-radius:15px" type="textbox" name="rest_example_3" id="rest_example_3" value="" /></td>
<td ><br><br><br></td>
</tr>
<tr>
<td><b>Bitiş Zamanı :</b> </td>
<td><input style="border-radius:15px" type="textbox" name="rest_example_4" id="rest_example_4" value="" /></td>
<td ><br><br><br></td>
</tr>
<tr>
<td ><br><br><br></td>
<td><input type="button" style="border-radius:15px; background-color:lightgreen; float:right" width="100" value="Get Chart" onClick="zaman_al()"> </td>
<td ><br><br><br></td>
</tr>
</table></center>
<div id="kku"></div>
When I sent to data mysql.php in the ($.POST), mysql.php is giving me notice:Undefined xxx.
mysql.php error statement
By the way, mysql.php is follow as:
<?php
$baslangic =$_POST['baslama']; // -> notice: Undefined index: baslama
$son=$_POST['bitirme']; // -> notice: Undefined index: bitirme
//$baslangic=1445780257; -> correct result for it
//$son=1445780290; -> correct result for it
//echo $son;
//echo $baslangic;
//settype($son, "int");
//settype($baslangic, "int");
//echo gettype(1445780290);
//echo gettype($son);
$baglanti= new mysqli("localhost","root","","deneme_kou");
$sql = "SELECT zaman,sensor_deger FROM sensor WHERE zaman>='$baslangic' AND zaman<='$son'";
$res=mysqli_query($baglanti,$sql);
$result = array();
while( $row = mysqli_fetch_array($res))
{
$result[]=array($row["zaman"],$row["sensor_deger"]);
}
$sonuc=json_encode(array($result));
echo json_encode(array($result));
?>
When I wrote $baslangic=1445780257 $son=1445780290; instead of $baslangic = $_POST['baslama']; $son=$_POST['bitirme'], I can get correct result and show in highchart.js.
Could you help me about this problem?
I'm looking to use highcharts to display quantity (0.0) and time (HH:MM).
The quantity and time will be selected from a database.
At this point I have made a working example but the data from the database is weight (0.0) and age (weeks). This data was easy to put into the chart and has worked perfectly. The code I have used for this is shown below;
<?php
session_start();
// Create connection
$con=mysqli_connect("localhost","username","password","database");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_SESSION['id'];
$response = mysqli_query($con,"SELECT b_id,weight,age FROM tbl WHERE id = '".$id."' ");
if(!$response)
{
die("<p>Error". mysqli_error($con)."</p>");
}
$weight = array();
$age = array();
while($result=mysqli_fetch_array($response))
{
$weight += [$result['b_id'] => $result['weight']];
$age += [$result['b_id'] => $result['age']];
}
?>
// High Chart //
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: ''
},
subtitle: {
text: ''
},
xAxis: {
categories: [<?php echo join($age, ',');?>],
crosshair: true
},
yAxis: {
min: 0,
title: {
text: ''
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: '',
data: [<?php echo join($weight, ',');?>]
}]
});
});
</script>
I now need to create a graph to show the quantity (0.0) and time (HH:MM) in a similar way. I know that the time must be converted into milliseconds for it to work with JavaScript for which I did find some code for from stack overflow courtesy of Tim Cooper:
<?php $str_time = $time;
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$time_seconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;
?>
I just need to know if and how to make this work with the highcharts in the way that I have used them using php rather than using JSON to get the data.
Also if instead i need to reformat the time(HH:MM) to milliseconds before it is inserted into the database so that it can be selected and put into the array to use with the highcharts?
I'm slightly new to JavaScript so if anyone has any hints or tips on how to get this graph to work - preferably using similar syntax to the first graph it would be much appreciated!
Thanks!
beginner here, I'm trying to build a column graph that shows a username on the x axis, and a test score on the y axis. In the tooltips box, I'm trying to make it so it shows the test score and the date the test was taken. I'm using PHP to populate the graph based on an oracle sql database, so I'm mixing PHP into my javascript for Highcharts.
I'm not sure if what I'm trying to do is actually possible, but I'm trying to take the test date from the sql database, and plug it into the series data, so I can call it out into the tooltips box (that way when you hover over the column, it'll tell you the user, the score, and the date they took the exam).
This is what I'm trying, and it isn't working, because I'm guessing series data has something against strings instead of numeric. Any help you can offer would be awesome! Thanks!
<br><br><br><br>
<div id="graph1" style="height: 400px; width: <?php echo $chartspace ?>px"></div>
<input id="width" type="range" value="<?php echo $chartspace ?>" min="300" max="<?php echo $chartspacemax ?>" />
<script>
$(function () {
$('#graph1').highcharts({
credits: { enabled:false},
chart: {
type: 'column'
},
title: {
text: 'Most Recent Test Scores'
},
subtitle: {
text: 'Drag slider to change the chart width'
},
xAxis: {
categories: [
<?php
$i = 0;
do {
echo "'";
echo $userinfos[$i]['username'];
echo "',";
$i++;
} while ($i<=$count); ?>
]
},
yAxis: {
plotLines: [{
color: 'red',
dashStyle: 'shortdash',
value: 85,
width: 1,
}],
floor: 0,
ceiling: 100,
title: {
text: 'Test Score (%)'
}
},
series: [{
showInLegend: false,
name: 'Test Score',
data: [
<?php
$i = 0;
do {
if($userinfos[$i]['score'] >= 85){
echo "{y:";
echo $userinfos[$i]['score'];
echo ", testdate:";
echo $userinfos[$i]['most_recent_test_date'];
echo ", color: '#00A6CF'},";}
else{
echo "{y:";
echo $userinfos[$i]['score'];
echo ", testdate:";
echo $userinfos[$i]['most_recent_test_date'];
echo ", color: 'red'},";}
$i++;
} while ($i<=$count-1); ?>]
}],
tooltip: {
shared: true,
useHTML: true,
pointFormat: '<tr><td style="color: {series.color}">Score: </td>' +
'<td style="text-align: right">{point.y} %</td></tr><tr><br><td>Date: </td>' +
'<td style="text-align: right">{point.testdate}</td></tr>'
}
});
$('#width').bind('input', function () {
$('#graph1').highcharts().setSize(this.value, 400, false);
});
});
</script>
What you're trying to do should definitely be possible. Here's an example of that working:
http://jsfiddle.net/thfbx7gb/
However, in this case I pulled out the PHP and replaced it with some hard-coded data.
data: [{y:7, color: '#00A6CF', testdate: '2014-12-12'},{y:2, color:"#FF0000", testdate: '2015-01-03'}, {y:3,color:"#00FF00", testdate:'2014-10-19'}]
So I think the problem is that you're mixing in PHP with javascript and getting some strange results. It's generally a very bad idea to include inline PHP into javascript code like you're doing if for no other reason that it's really, really hard to read and debug.
A few things jump out at me:
You shouldn't be using PHP for this at all, but if you must then you shouldn't be using do-while loops like you are. You're using a do/while with an incrementor instead of a for loop:
$i = 0;
do {
echo "'";
echo $userinfos[$i]['username'];
echo "',";
$i++;
} while ($i<=$count);
This should really be:
for ($i=0; $i<=$count; $i++) {
echo "'{$userinfos[$i]['username']}'";
}
You should be able to see how the other do/while loops you're using could be reduced to a much more succinct for loop.
But that still doesn't eliminate the whole problem of including PHP code in your javascript. You should really be either hard coding this data or loading it from an external source of some kind. The typical way of doing that would be with an AJAX call to load the data and then pass that in to the chart directly.
You would have a file that generates the data object directly and outputs that as as JSON string using json_ecode();
$output = array();
foreach ($userinfos as $user) {
$output['categories'][] = $user['username'];
if ($user['score'] >= 85) {
$color = "#00A6CF";
} else {
$color = "#FF0000";
}
$user['color'] = $color;
$output['seriesdata'][] = $user;
}
echo json_encode($output);
This should give you a JSON object which you can read work with pretty easily. Something along the lines of this (which is untested, it may not work without a bit of fiddling):
$.getJSON('/generate.php', function(data) {
$('#graph1').highcharts({
credits: { enabled:false},
chart: {
type: 'column'
},
title: {
text: 'Most Recent Test Scores'
},
subtitle: {
text: 'Drag slider to change the chart width'
},
xAxis: {
categories: data.categories
yAxis: {
plotLines: [{
color: 'red',
dashStyle: 'shortdash',
value: 85,
width: 1,
}],
floor: 0,
ceiling: 100,
title: {
text: 'Test Score (%)'
}
},
series: [{
showInLegend: false,
name: 'Test Score',
data: data.seriesdata,
tooltip: {
shared: true,
useHTML: true,
pointFormat: '<tr><td style="color: {series.color}">Score: </td>' +
'<td style="text-align: right">{point.y} %</td></tr><tr><br><td>Date: </td>' +
'<td style="text-align: right">{point.testdate}</td></tr>'
}
});
});
I am trying to have a graph display registration data generated from the mysql database. The format for data seems to be coming out correctly but the data is not being plotted. Please note that I am using CodeIgniter.
PHP:
public function graph_registrations()
{
$send = array();
$i = 1;
while($i <= 30){
$startTime = mktime(0, 0, 0, date('m'), date('d')-$i, date('Y'));
$endTime = mktime(23, 59, 59, date('m'), date('d')-$i, date('Y'));
$data = $this->admin_model->total_users_date($startTime, $endTime);
$new = array(date("M j", $startTime), $data);
$send[] = $new;
$i++;
}
echo json_encode($send);
}
JS:
var jsonData = $.ajax({
url: default_url+"admin/graph_registrations",
dataType:"json",
async: false
}).responseText;
console.log(jsonData);
var graphData = [{
// Visits
data: jsonData,
color: '#71c73e',
points: { radius: 4, fillColor: '#71c73e' }
}
];
// Lines
$.plot($('#graph-lines'), graphData, {
series: {
points: {
show: true,
radius: 5
},
lines: {
show: true
},
shadowSize: 0
},
grid: {
color: '#646464',
borderColor: 'transparent',
borderWidth: 20,
hoverable: true
},
xaxis: {
tickColor: 'transparent',
tickDecimals: 2
},
yaxis: {
tickSize: 1000
}
});
Everything works if I manually hard code the data in, but not when I grab it via ajax.
This is what console.log(jsonData) produces:
[["Dec 5",0],["Dec 4",0],["Dec 3",0],["Dec 2",0],["Dec 1",0],["Nov 30",0],["Nov 29",0],["Nov 28",0],["Nov 27",0],["Nov 26",0],["Nov 25",0],["Nov 24",0],["Nov 23",0],["Nov 22",0],["Nov 21",0],["Nov 20",0],["Nov 19",0],["Nov 18",0],["Nov 17",0],["Nov 16",0],["Nov 15",0],["Nov 14",0],["Nov 13",0],["Nov 12",0],["Nov 11",0],["Nov 10",0],["Nov 9",1],["Nov 8",0],["Nov 7",0],["Nov 6",0]]
I tried doing it without the date and just a plain number, but it did not work.
Thank you
For me you are trying to plot the data before having them. I can see you are using "async:false" to wait for the data to be loaded by I'd rather used the default "true" option and placed the plotting function in "success" callback of $.ajax.