modify Xaxis in highcharts - javascript

How can I introduce in the highcharts code an array that comes from a php code?
In the next code php I generate 4 arrays, 3 for Data (TMax ($rows), TMin ($rows1) and Rain ($rows2) and the last one for the days of the consulting ($dia).
$sth = mysqli_query($con,"SELECT City,TMax, Day(Date) As Dia FROM Meteo2 where City= '" . $_SESSION["City"] ."' AND Data BETWEEN '" . split($_SESSION["date8"]) ."' AND '" . split($_SESSION["date9"]) ."'order by Date");
$rows = array();
$dia = array();
$dia['name'] = 'Dia';
$rows['name'] = 'TMAX';
$rows['color'] = '#FF0000';
$cont=1;
while($r = mysqli_fetch_array($sth)) {
$rows['data'][] = $r['TMax'];
$dia['categories'][] = $r['Dia'];
}
$sth = mysqli_query($con,"SELECT City,TMin FROM Meteo2 where City= '" . $_SESSION["City"] ."' AND Data BETWEEN '" . split($_SESSION["date8"]) ."' AND '" . split($_SESSION["date9"]) ."'order by Date");
$rows1 = array();
$rows1['name'] = 'TMIN';
$rows1['color'] = '#00FFFF';
$rows1['var valueSuffix'] = 'ºC';
while($rr = mysqli_fetch_assoc($sth)) {
$rows1['data'][] = $rr['TMin'];
}
mysqli_query($con,"SELECT City,Rain FROM Meteo2 where City= '" . $_SESSION["City"] ."' AND Data BETWEEN '" . split($_SESSION["date8"]) ."' AND '" . split($_SESSION["date9"]) ."'order by Date");
$rows2 = array();
$rows2['name'] = 'RAIN';
$rows2['type'] = 'column';
$rows2['color'] = '#4572A7';
$rows2['var valueSuffix'] = 'mm';
$rows2['var yAxis'] = 2;
while($rr = mysqli_fetch_assoc($sth)) {
$rows2['data'][] = $rr['Rain'];
}
$result = array();
array_push($result,$rows2);
array_push($result,$rows1);
array_push($result,$rows);
array_push($result,$dia);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>
When I plot the chart, I can see the line of rain, TMax, TMin, but in the Xaxis by default I have 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15....and what I need is the information of $dia inside categories[]
and when i check the browser I see categories empty...
xAxis: {
categories: []
},
but in the highchart code I have
xAxis: {
categories: ['<?php echo $dia?>']
},
any help please????
Here I show the highcharts code
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>www.meteo4u.com/consultaNouformat.html</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript">
<?php
$city = $_POST["City"];
session_start();
$_SESSION['City'] = $_POST['City'];
$_SESSION['date8'] = $_POST['date8'];
$_SESSION['date9'] = $_POST['date9'];
?>
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("mysql-highcharts.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'spline',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Temperatura Maxima, Temperatura Minima i Precipitacio a <?php echo $city ?>',
x: -20 //center
},
xAxis: {
categories: [<?php echo $dia?>]
},
yAxis: [{
labels: {
format: '{value}°C',
style: {
color: '#FF0000'
}
},
title: {
text: 'Temperatura Maxima',
style: {
color: '#FF0000'
}
}
},{title: {
text: 'Temperatura Minima',
style: {
color: '#00FFFF'
}
}
},{labels: {
format: '{value} mm',
style: {
color: '#4572A7'
}
},
title: {
text: 'Precipitacio',
style: {
color: '#4572A7'
}
},opposite: true
}],
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
credits:{
text: 'meteo4u.com',
href:'http://meteo4u.com',
itemStyle: {
fontSize: '40px'
}
},
series: json
});
});
});
});
</script>
</head>
<body>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>

It looks like $dia is an array is an array, containing an entry called 'categories'. I don't think you can somply echo the array variable in your highcharts code, as dia only exists in php on the server. You are returning the categories inside your json object in the 3rd entry of the array
array_push($result,$dia);
This means you have to read the categories out of the returned json in your highcharts code. Your code is hard to follow, but try this:
xAxis: {
categories: json[3]['categories'];
},
However, I am worried about this line:
series: json
The returned json does not just contain series definitions as it contains the categories as well. It may work, but is not very clean code.

Related

Creating multiple series in chart

I don't know how to create multiple series with data.I manage to do with only on ID from table. But when I have to take all data for every ID , didnt work.
This is php code
<?php include 'login/dbconf.php';
$conn = mysqli_connect($host, $username, $password, $db_name);
$conn->query("SET NAMES utf8");
$external_cow_id = $_POST['external_cow_id'];
$query = "SELECT testing_date, delta_mp FROM cow_result WHERE id='{$id}'";
$result = mysqli_query($conn, $query);
if ( ! $result ) {
echo mysqli_error();
die;
}
$testing_date = array();
$delta_mp = array();
for ($x = 0; $x < mysqli_num_rows($result); $x++) {
$data = mysqli_fetch_assoc($result);
$testing_date[]=$data['testing_date'];
$delta_mp[]=$data['delta_mp'];
}
//echo json_encode($data);
mysqli_close($server);
?>
And this is js I use for one cow only.
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
backgroundColor: null
},
title: {
text: 'FPA RESULTS',
style: {
color: '#000'
}
},
xAxis: {
categories: <?php echo json_encode($testing_date); ?>
},
yAxis: {
labels: {
style: {
color: '#CCC'
},
},
gridLineColor: '#333'
},
series: [{
name:[<?php echo json_encode($external_cow_id); ?>] ,
data: [<?php echo join($delta_mp, ',') ?>],
color: 'blue',
shadow: {
color: 'blue',
width: 10,
offsetX: 0,
offsetY: 0
}
}]
});
And I need something like this
chart
Every cow has multiple testing_date and delta_mp...
Thanks for help

highchart.js is not working. error 13

This is the image of the error:
This error 13 is always showing up. I just cannot find the reason why highchart.js is not working. Can anyone help me to fix this one? Thanks
<?php
$q = $this->db->query("select * from scli_tbl_services");
foreach ($q->result() as $row) {
$data[] = $row->service_id;
}
?>
<script type="text/javascript">
var chart = new Highcharts.Chart({
chart: {
renderTo: 'chart_sample'
},
series: [{
data: [<?php echo join($data, ',') ?>],
pointStart: 0,
pointInterval: 10
}]
});
</script>
<span id="chart_sample" class="chart_sample"></span>
This is my code that I'm about to run. So I don't know if my code also is working fine.
HighChart.Js Solution :
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<div id="container" style="height: 300px"></div>
<?php
$newArray = array(
"Valvo" => Array(10,15,20),
"ACBUS" => Array(25,30,15),
"SchoolBus" => Array(25,30,15),
"MiniBus" => Array(25,30,15),
"CityBus" => Array(25,30,15)
);
$json_array_form = array();
$data = '';
foreach ($newArray as $key => $value){
$json_array_form['name'] = $key;
$json_array_form['data'] = $value;
$data .= json_encode($json_array_form).',';
}
$data = substr($data, 0, -1);
?>
//HighChart Js functionality start
<script>
$(function () {
$('#container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: ['Apples', 'Bananas', 'Oranges']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [<?php echo $data;?>],
});
});
</script>

Loop inside Jquery Chart to make it dynamic

Im new in Js and Jquery and I have a curiosity about the Jquery Chart that is free to download and I want to make the data inside to be coming from the database to make it dynamic but somehow I find it difficult to loop it in.
here is my sample code, I used PHP to get the database and pass it on a JS variable
<!DOCTYPE HTML>
<html>
<head>
<?php
$link = mysqli_connect("localhost","root","","raksquad_centralized") or die("Error " . mysqli_error($link));
if($link->connect_error){
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM raksquad_centralized.grade";
$result = $link->query($query);
$subject_id= array();
$genAve = array();
while($row = mysqli_fetch_array($result)){
$subject_id[] = $row['subject_id'];
$genAve[]= $row['gen_ave'];
}
?>
<script type="text/javascript">
window.onload = function () {
var DataXAxis = <?php echo json_encode($subject_id); ?>; // X axis that corresponds to students
var DataYAxis = <?php echo json_encode($genAve); ?>; // Y axis that corresponds to grades
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "Top Students"
},
animationEnabled: true,
axisY: {
title: "Grades"
},
axisX: {
title: "Students"
},
legend: {
verticalAlign: "bottom",
horizontalAlign: "center"
},
theme: "theme2",
data: [
{
type: "column",
showInLegend: true,
legendMarkerColor: "grey",
legendText: "General Average",
dataPoints: [
//the area to loop with the value of DataXAxis, DataYAxis
{y: 98, label: "MT1234" },
{y: 72, label: "MT1236"} //corresponds to the barcharts
]
}
]
});
chart.render();
}
</script>
<script type="text/javascript" src="./canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
</body>
</html>
appreciate for the help, useful for learning :)
I just use a php code to fetch the data, then json encode it.
On the script use json parse

Passing data with a search variable to Highcharts not working

As said in the title, I'm actually making a small application where you can look for a random name into a database and it shows you the adequate chart (the chart that shows the searched name's data).
It works well when I tried that by puting a static name in my data.php file (from where the chart takes the data). But when I used $_GET[ 'search' ] instead it didn't show anything. (I checked my data.php and it returns the JSON correctly) so I guess it comes from HighCharts.
Do you by chance know what could be the problem please?
Here's some parts of my code so you can understand what I'm saying.
data.php
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=nsui', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$sql=<<<SQL
SELECT `Period_start_time`, `Segment_Name`,
`csf_bh`, `drp_sd_bh`, `ec_tch_bh`, `ec_hors_cong_bh`
FROM `call_succes`
WHERE `Segment_Name`='{$search}'
SQL;
$reponse = $bdd->query($sql);
$bln = array();
$bln['name'] = 'Period_start_time';
$rows1['name']='csf_bh';
$rows2['name']='drp_sd_bh';
$rows3['name']='ec_tch_bh';
$rows4['name']='ec_hors_cong_bh';
while($donnee=$reponse->fetch()){
$bln['data'][] = $donnee['Period_start_time'];
$rows1['data'][] = $donnee['csf_bh'];
$rows2['data'][] = $donnee['drp_sd_bh'];
$rows3['data'][] = $donnee['ec_tch_bh'];
$rows4['data'][] = $donnee['ec_hors_cong_bh'];
}
$rslt = array();
array_push($rslt, $bln);
array_push($rslt, $rows1);
array_push($rslt, $rows2);
array_push($rslt, $rows3);
array_push($rslt, $rows4);
print json_encode($rslt, JSON_NUMERIC_CHECK);
$reponse->closeCursor();
?>
chart.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container_call',
type: 'line'
},
title: {
text: 'Call Setup Failure',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: [],
title: {
text: 'Date'
}
},
yAxis: {
labels: {
format: '{value} %'
},
min: 0,
title: {
text: 'Percentage (%)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: '%',
shared: true
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: []
};
$.getJSON("data.php", function(json) {
options.xAxis.categories = json[0]['data']; //xAxis: {categories: []}
options.series[0] = json[1];
options.series[1] = json[2];
options.series[2] = json[3];
options.series[3] = json[4];
chart = new Highcharts.Chart(options);
});
});
</script>
In my search page I've put a code like :
<?php
...
...
global $search;
$button = $_GET [ 'submit' ];
$search = $_GET [ 'search' ];
...
...
$html.=<<<HTML
<div class="box alt">
<div class="row 50% uniform">
<div id="container_call" class="6u 6u(xsmall)">
HTML;
include ('chart.php');
$html.=<<<HTML
</div>
</div>
</div>
...
?>
And of course with the adequate javascript for highcharts etc. When I click on the button search in my home page it redirects me to my search page.
Thank you in advance.

Highcharts Dynamic Chart with MySQL Data doesn't reload

Good evening everyone,
this moment I try to work with HighChart / HighStock and after several weeks I were able to display my MySQL-data in the charts. But: I always want more.
Well, I try to reach a dynamic chart which is refreshing like the examples you may know from the website. http://jsfiddle.net/sdorzak/HsWF2/
I used the sample code as a guide. It doesn't work, but think the problem is the missing y-axis because y-axis data come from my MySQL database while x-axis should be the current time.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>POS RESULT</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<?php
include "config.php";
$SQL1 = "SELECT * FROM Prices WHERE ticker ='FB'";
$result1 = mysql_query($SQL1);
$data1 = array();
while ($row = mysql_fetch_array($result1)) {
$data1[] = $row['Close'];
}
?>
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 130,
marginBottom: 25,
events: {
load: function()
{
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime();
series.addPoint([x], true);
}, 1000);
},
title: {
text: 'Monthly Average Temperature',
x: -20 //center
},
subtitle: {
text: 'Source: WorldClimate.com',
x: -20
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
//categories: [<?php echo join(',', $data2); ?>],
},
yAxis: {
title: {
text: 'Temperature (°C)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y +'°C';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
name: 'Tokyo',
data: [<?php echo join(',', $data1); ?>]
}]
});
});
});
</script>
<div id="container" style="min-width: 500px; height: 400px; margin: 0 auto"></div>
</body>
</html>
The passage I am talking about and which is shown in the samples is
chart: {
renderTo: 'container',
type: 'spline',
marginRight: 10,
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, true);
}, 1000);
}
}
But, as I already wrote, I don't need a random y-axis, just x-axis.
Maybe you can help.
Thanks for your help.
Edit:
live-server-data.php
<?php
// Set the JSON header
header("Content-type: text/json");
include "config.php";
$SQL1 = "SELECT * FROM Prices WHERE Ticker ='TSLA'";
$result1 = mysql_query($SQL1);
while ($row = mysql_fetch_array($result1)) {
$data1[] = $row['Close'];
}
// 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 = $data1;
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>
The value "Close" is decimal 24,4.
See that solution: http://www.highcharts.com/studies/live-server.htm
var chart; // global
/**
* Request data from the server, add it to the graph and set a timeout to request again
*/
function requestData() {
$.ajax({
url: 'live-server-data.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(eval(point), true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
im trying to create another page that can relate to my bar chart. You can go through his code. It work for me
<!DOCTYPE html>
<html>
<head>
<?php
session_start();
?>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script>
$('#calendar').datepicker({
});
!function ($) {
$(document).on("click","ul.nav li.parent > a > span.icon", function(){
$(this).find('em:first').toggleClass("glyphicon-minus");
});
$(".sidebar span.icon").find('em:first').addClass("glyphicon-plus");
}(window.jQuery);
$(window).on('resize', function () {
if ($(window).width() > 768) $('#sidebar-collapse').collapse('show')
})
$(window).on('resize', function () {
if ($(window).width() <= 767) $('#sidebar-collapse').collapse('hide')
})
</script>
<style>
.selection{
border: 1px solid gray;
border-radius: 10px;
padding: 10px;
text-decoration:none;
float:left;
margin:4px;
text-align:center;
display: block;
color: green;
}
.page-header{
text-align:center;
text-decoration:hover;
color: blue;
font-size: 30px;
}
</style>
<script>
$(function () {
//on page load
getAjaxData(1);
//on changing select option
$('#dynamic_data').change(function(){
var val = $('#dynamic_data').val();
getAjaxData(val);
});
function getAjaxData(id){
//use getJSON to get the dynamic data via AJAX call
$.getJSON('datab1.php', {id: id}, function(chartData) {
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Analysis of Data Type in The World'
},
xAxis: {
categories: ['Population', 'Health', 'Agriculture', 'Development', 'Transport', 'Education', 'Social', 'Tourism', 'Finance','Business','Economy', 'Industry', 'Employment', 'Weather', 'Food', 'Energy', 'Infrastructure', 'Science&Technology', 'Government','Culture', 'Religion',
'Justice&Law', 'Country', 'Water Resource', 'Maritim', 'Military', 'International', 'Geography', 'Statistics', 'Others','Electronic','Biotechnology', 'Women', 'Gender', 'Cartography','Disability','Position','Marital','CDF','Research']
},
yAxis: {
min: 0,
title: {
text: 'Percentage (%)'
}
},
legend: {
enabled: false
},
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} %</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: chartData
});
});
}
});
</script>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div id="container" style="width: 100%; min-height: 500px; margin: 0 auto"></div>
</body>
</html>
And this the code for fetching data from mysql
<?php
require('dbcon.php');
//select database
//define array
//we need two arrays - "male" and "female" so $arr and $arr1 respectively!
$arr = array();
$result = array();
//get the result from the table "highcharts_data"
$sql = "select * from world";
$q = mysqli_query($con, $sql) or die(mysqli_error());
$j = 0;
while ($row = mysqli_fetch_assoc($q)) {
//highcharts needs name, but only once, so give a IF condition
if ($j == 0) {
$arr['name'] = 'Percentage';
$j++;
}
//and the data for male and female is here
$arr['data'][] = $row['datavalue'];
}
//after get the data for male and female, push both of them to an another array called result
array_push($result, $arr); //1
//now create the json result using "json_encode"
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>

Categories