web page doesn't display chart or any error - mysql

I just started my adventure with chartsjs. I tried to modify all tutorials I found to suit my needs, but unfortunately the page doesn't display the chart and doesn't give any errors. Can anyone advice please.
$result='';
$sql="SELECT Q1.uUserName AS Technician, sum(if(Q2.dCatFK=1,1,0)) AS AM, sum(if(Q2.dCatFK=2,1,0)) as PM
FROM T_users as Q1 LEFT JOIN (SELECT dUser2FK, dCatFK FROM T_Defects
INNER JOIN T_settings WHERE (dDateClosed >= FYDateFROM AND dDateClosed <= FYDateTO)";
if (!empty($_SESSION['dept'])) { $sql .= ' AND dDeptFK = '.$_SESSION['dept'];}
if (!empty($_SESSION['area'])) { $sql .= ' AND dAreaFK = '.$_SESSION['area'];}
if (!empty($_SESSION['month'])){ $sql .= ' AND MONTH(dDateClosed) = '.$_SESSION['month'];}
$sql .=") as Q2 ON Q1.uPK = Q2.dUser2FK GROUP BY Q1.uUserName ORDER BY sum(if(dCatFK is not null,1,0)) DESC, Q1.uUsername;";
try{
$stmt = $con->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$label = array();
$data = array();
foreach ($result as $row) {
$label[] = $row["Technician"];
$data[] = $row["AM"];
$data[] = $row['PM'];
}
} catch(PDOException $e){
echo 'ERROR: ' . $e->getMessage();
}
<canvas id="myChart_Fixed" width="1000" height="400"></canvas>
<script>
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var ctx = document.getElementById("myChart_Fixed");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels:<?=json_encode($label);?>,
datasets: [{
label: 'Fixed AM',
data:<?=json_encode(array_values($data[0]));?>,
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
},
{
label: 'Fixed PM',
data:<?=json_encode(array_values($data[1]));?>,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
</script>

you're appending your $data with AM and PM data so there are no 2 datasets instead there is only one dataset. Because of that $data[1] doesn't exists. Declare another 2 arrays and insert there your data for AM and PM respectively, then insert $dataAM at $data[0]... Let the code speak for itself:
...PHP file
$data = array();
$dataAM = array();
$dataPM = array();
foreach ($result as $row) {
$label[] = $row["Technician"];
$dataAM[] = $row["AM"];
$dataPM[] .=$row['PM'];
}
$data[0] = $dataAM;
$data[1] = $dataPM;
...HTML File
data: {
labels:<?=json_encode($label);?>,
datasets: [{
label: 'Fixed AM',
data:<?=json_encode(array_values($data[0]));?>,
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
},
{
label: 'Fixed PM',
data:<?=json_encode(array_values($data[1]));?>,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1
}
]
},

Typo error, changed this:
json_encode(array_values($data[0]))
to this:
json_encode(array_values($data))

Related

How to reset chart.js chart yAxes count on tab change in angular?

I am using chart.js in Angular for display data.
Is there any way to reset yAxes data on change tab?
Here's a link for Stackblitz demo.
On load I am getting data like this.
Than if i change tab than data are coming perfectly like below image.
But when I change tab again to first tab at that time data is coming perfect but yAxes data is not changing therefore my chart is looks deferent from initial load. like below image.
HTML CODE
<mat-tab-group #tabgroup2 class="chart-filter-list" (selectedTabChange)="onTabChanged($event);">
<mat-tab label="{{'This Week' | translate}}"></mat-tab>
<mat-tab label="{{'This Month' | translate}}"></mat-tab>
<mat-tab label="{{'This Year' | translate}}"></mat-tab>
</mat-tab-group>
<div class="chart-body">
<canvas baseChart
[datasets]="recruitingChartData"
[labels]="recruitingChartLabels"
[options]="recruitingChartOptions"
[legend]="recruitingChartLegend"
[plugins]="recruitingChartPlugins"
[colors]="recruitingChartColors"
[chartType]="recruitingChartType">
</canvas>
</div>
ts file code
onTabChanged($event) {
const eventLabel = $event.tab.textLabel
if (eventLabel == 'This Year'){
this.tabSelectValue = 'yearly'
}else if (eventLabel == 'This Month'){
this.tabSelectValue = 'monthly'
}else {
this.tabSelectValue = 'weekly'
}
this.getDashboardMainData({});
}
// Recruiting Chart
public recruitingChartGetData : any = [];
public recruitingOpeningData : any = [];
public recruitingCandidateData : any = [];
public recruitingApplicationData : any = [];
public recruitingChartData: any = [
{ data: [ ], label: this.translate.instant('Job Openings') },
{ data: [ ], label: this.translate.instant('Candidates') },
{ data: [ ], label: this.translate.instant('Job Applications') },
];
public recruitingChartColors: any = [
{ // grey
backgroundColor: 'rgba(255, 99, 71, 0)',
borderColor: '#262f79',
pointBackgroundColor: 'rgba(148,159,177,1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(148,159,177,0.8)'
},
{ // Blue
backgroundColor: 'rgba(255, 99, 71, 0)',
borderColor: '#fdb167',
pointBackgroundColor: 'rgba(148,159,177,1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(148,159,177,0.8)'
},
{ // red
backgroundColor: 'rgba(255, 99, 71, 0)',
borderColor: '#30c76f',
pointBackgroundColor: 'rgba(148,159,177,1)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgba(148,159,177,0.8)'
}
];
public recruitingChartLabels: any = [];
public recruitingChartOptions = {
responsive: true,
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
},
};
public recruitingChartLegend = false;
public recruitingChartType: any = 'line';
public recruitingChartPlugins = [];
You need to also re-initialize recruitingChartData each time a new tab is selected. This can be done inside getDashboardMainData as follows.
async getDashboardMainData(request): Promise<void> {
...
this.recruitingChartData.forEach(o => o.data = []);
Please take a look at your amended StackBlitz and see how it works.

get the count of dayname Failed - Laravel 9

For my case , I have a data table contains a timestamps data call "created_at" , right now , it want to get the count of the dayname of the time stamp
so ideally it will be like
and I like to save it on the array for me to pass the data to may chart.js chart
so what i do is
$getdate = DB::table('watchlists')
->select('created_at')
->get();
$getweekday = Carbon::parse($getdate)->format('l');
$dayarray=[];
if($getweekday =='Monday')
{
$mondaycount = Carbon::parse($getdate)->count();
$dayarray=[0];
}
elseif($getweekday =='Tuesday')
{
$tuesday = Carbon::parse($getdate)->count();
$dayarray=[1];
}
elseif($getweekday =='Wednesday')
{
$wednesday = Carbon::parse($getdate)->count();
$dayarray=[2];
}
elseif($getweekday =='Thursday')
{
$thursday = Carbon::parse($getdate)->count();
$dayarray=[3];
}
elseif($getweekday =='Friday')
{
$firday = Carbon::parse($getdate)->count();
$dayarray=[4];
}
elseif($getweekday =='Saturday')
{
$saturday = Carbon::parse($getdate)->count();
$dayarray=[5];
}
elseif($getweekday =='Sunday')
{
$sunday = Carbon::parse($getdate)->count();
$dayarray=[6];
}
<script>
const ctx = document.getElementById('chart1').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
datasets: [{
label: 'Visitor Volume by weekday',
data: [{{ $dayarray}}],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
but when i try to run the code it gives the error of
Could not parse '[{"created_at":"2022-06-24 18:50:05"},{"created_at":"2022-06-26 13:24:42"},{"created_at":"2022-06-24 18:50:05"},{"created_at":"2022-06-26 13:24:42"},{"created_at":"2022-06-26 13:24:42"},{"created_at":"2022-06-26 13:24:42"}]': DateTime::__construct(): Failed to parse time string ([{"created_at":"2022-06-24 18:50:05"},{"created_at":"2022-06-26 13:24:42"},{"created_at":"2022-06-24 18:50:05"},{"created_at":"2022-06-26 13:24:42"},{"created_at":"2022-06-26 13:24:42"},{"created_at":"2022-06-26 13:24:42"}]) at position 0 ([): Unexpected character
I like to ask what is the error in the code , did I miss anything?
PS. I would also like to ask how to pass the data to the charts . i have a premade charts
You can use array reduce() function for this purpose. It is a php array function that you can find docs in here and also for laravel collection
$dayCounts = DB::table('watchlists')
->select('created_at')
->get()
->reduce(function ($car, $item) {
$day = Carbon::parse($item->created_at)->format('l');
$car[$day] = ($car[$day] ?? 0) + 1;
return $car;
});

How I create a dropdown for radar chartjs from mysql database?

I have a mysql database named players and with these columns id, name, attack, defence, speed, dribbling and shoot.
I create a radar chart to show players data.
My code is this:
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>
<script type="text/javascript">
let json = <?php include("datas.php");?>;
let label = [];
let data = [];
// generate label and data dynamically
json.forEach(e => {
label.push(e.name);
data.push([+e.attack, +e.defence, +e.speed, +e.shoot, +e.dribbling]);
});
let ctx = document.querySelector('#canvas').getContext('2d');
let chart = new Chart(ctx, {
type: 'radar',
data: {
labels: ['attack', 'defence', 'speed','shoot','dribbling'],
datasets: [{
label: label[0],
data: data[0],
backgroundColor: 'rgba(0,119,204,0.2)',
borderColor: 'rgba(0,119,204, 0.5)',
borderWidth: 1,
pointBackgroundColor: 'rgba(0, 0, 0, 0.5)'
}, {
label: label[1],
data: data[1],
backgroundColor: 'rgba(255, 0, 0 ,0.15)',
borderColor: 'rgba(255, 0, 0 ,0.45)',
borderWidth: 1,
pointBackgroundColor: 'rgba(0, 0, 0, 0.5)'
}, {
label: label[2],
data: data[2],
backgroundColor: 'rgba(0,119,204,0.2)',
borderColor: 'rgba(255, 0, 0 ,0.45)',
borderWidth: 1,
pointBackgroundColor: 'rgba(0, 0, 0, 0.5)'
}]
},
options: {
title: {
display: true,
position: "top",
text: "Radar test",
fontSize: 14,
fontColor: "#111"
},
legend: {
display: true,
position: "bottom"
},
scale: {
pointLabels: {
fontSize: 11
}
}
}
});
</script>
</body>
</html>
Datas.php:
<?php
$conn = mysqli_connect("localhost","root","","players");
$sqlQuery = "SELECT * FROM players_attributes ORDER BY id";
$result = mysqli_query($conn,$sqlQuery);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
echo json_encode($data);
?>
My question is how to create a radar chart with a dropdown filter by name?
The dropdown should show the list of players and the radar chart change for selected player.
Try this code: Datas.php
<?php
$conn = mysqli_connect("localhost","root","","players");
$sqlQuery = "SELECT id, name FROM players_attributes ORDER BY id";
$result = mysqli_query($conn,$sqlQuery);
$data = array();
foreach ($result as $row) {
echo "<option data-id='".$row['id']."' value='" . $row['name'] ."'>";
}
echo json_encode(array('data'=>$row));
?>

Highcharts with json from django query not rendered

I'm following this article to render highchart with json data from django query. However chart is not rendered but I'm not getting any errors from Django or by the client when inspecting source. Appreciate if anyone can point the mistakes. Thank you in advance.
I'm using django 2.0 and python3.5
models.py
PLATFORM = (
('ipcore','IPCORE'),
('metro','METRO E'),
('edge','EDGE'),
('access','ACCESS'),
('voice','VOICE'),
('system','SYSTEM'),
('iptv','IPTV'))
class Contract(models.Model):
vendor_name = models.ForeignKey(Vendor, on_delete=models.CASCADE)
name = models.CharField(max_length=500)
contract_no = models.CharField(max_length=100, blank=True)
partner_name = models.CharField(max_length=200, blank=True)
value = models.DecimalField(max_digits=11, decimal_places=2,
blank=True, null=True)
platform = models.CharField(max_length=100, blank=True,
choices=PLATFORM)
views.py
def json_example(request):
return render(request, 'app/json_example.html')
def chart_data(request):
dataset=Contract.objects.all().values('platform').
exclude(platform='').annotate(Sum('value')).order_by('value__sum')
platform_name = dict()
for platform_tuple in Contract.PLATFORM:
platform_name[platform_tuple[0]] = platform_tuple[1]
chart = {
'chart': {'type': 'pie'},
'title': {'text': 'Contract Value for Every platform'},
'series': [{
'name': 'Platform',
'data': list(map(lambda row: {'name':
platform_name[row['platform']],
'y': row['value__sum']}, dataset))
}]
}
return JsonResponse(chart)
urls.py
url('json_example/', views.json_example, name='json_example'),
url('json_example/data/', views.chart_data, name='chart_data'),
json_example.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Contract Inventory Highcharts Example</title>
</head>
<body>
<div id="container" data-url="{% url 'chart_data' %}"></div>
<script src="https://code.highcharts.com/highcharts.src.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$.ajax({
url: $("#container").attr("data-url"),
dataType: 'json',
success: function (data) {
Highcharts.chart("container", data);
}
});
</script>
</body>
</html>
This is the json data from dataset.
[{"platform": "IPTV", "value__sum": "0.00"}, {"platform": "METRO E", "value__sum": "71372564.20"}, {"platform": "EDGE", "value__sum": "73867073.63"}, {"platform": "SYSTEM", "value__sum": "135465418.85"}, {"platform": "IPCORE", "value__sum": "467810178.41"}]
This is the json data from dataset.
[{"platform": "IPTV", "value__sum": "0.00"}, {"platform": "METRO E", "value__sum": "71372564.20"}, {"platform": "EDGE", "value__sum": "73867073.63"}, {"platform": "SYSTEM", "value__sum": "135465418.85"}, {"platform": "IPCORE", "value__sum": "467810178.41"}]
Your json data doesn't contain chart options. It should be something like this:
'{"title":{"text":"Title"},"series":[{"name":"Installation","data":[43934,52503,57177,69658,97031,119931,137133,154175]}]}'
What's more, you should parse json to js object before passing it to Highcharts constructor:
<script>
$.ajax({
url: $("#container").attr("data-url"),
dataType: 'json',
success: function (data) {
var chartData = JSON.parse(data);
Highcharts.chart("container", chartData);
}
});
</script>
Check the example:
https://jsfiddle.net/BlackLabel/7zfyhnbr/
You have to format the data in such a way that it should match the highcharts ploting object. Please checkout the below code.
data = [
{"platform": "IPTV", "value__sum": "0.00"},
{"platform": "METRO E", "value__sum": "71372564.20"},
{"platform": "EDGE", "value__sum": "73867073.63"},
{"platform": "SYSTEM", "value__sum": "135465418.85"},
{"platform": "IPCORE", "value__sum": "467810178.41"}];
x_axis_data = [];
y_axis_data = [];
for(index=0; index < data.length; index++) {
item = data[index];
x_axis_data.push(item['platform'])
y_axis_data.push(parseFloat(item['value__sum']))
}
Highcharts.chart('container', {
title: {
text: 'learnbatta.com'
},
xAxis: {
title: {
text: 'X Value'
},
categories: x_axis_data
},
yAxis: {
title: {
text: 'Y Value'
},
},
series: [{
name: 'Curve',
data: y_axis_data
}]
});
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="container"></div>
</body>
</html>
You have to update your code like below
<script>
$.ajax({
url: $("#container").attr("data-url"),
dataType: 'json',
success: function (data) {
var data = JSON.parse(data);
x_axis_data = [];
y_axis_data = [];
for(index=0; index < data.length; index++) {
item = data[index];
x_axis_data.push(item['platform'])
y_axis_data.push(parseFloat(item['value__sum']))
}
Highcharts.chart('container', {
title: {
text: 'learnbatta.com'
},
xAxis: {
title: {
text: 'X Value'
},
categories: x_axis_data
},
yAxis: {
title: {
text: 'Y Value'
},
},
series: [{
name: 'Curve',
data: y_axis_data
}]
});
}
});
</script>
I've manage to solve it by updated my views.py using django rest API and my template accordingly. Here is my updated code:
views.py
from rest_framework.views import APIView
from rest_framework.response import Response
class ChartView(View):
def get(self, request, *args, **kwargs):
return render(request, 'app/charts.html')
class ChartData(APIView):
authentication_classes = []
permission_classes = []
def get(self, request, format=None):
totalvendor= Contract.objects.all().values("vendor_name_id__name").
annotate(Count("id")).order_by('-id__count')[:8]
labels = totalvendor.values_list('vendor_name_id__name')
default_items = totalvendor.values_list('id__count', flat=True)
default_items = list(default_items)
data = {
"labels": labels,
"default": default_items,
}
return Response(data)
Pass an array from queryset to template and js
Here is my urls.py
url(r'^chart/', views.ChartView.as_view(), name='chart'),
url(r'^api/chart/data/$', ChartData.as_view(), name='chartdata'),
Here my code for charts.html
<script>
{% block jquery %}
var endpoint = '/api/chart/data/'
var defaultData = []
var labels = [];
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
labels = data.labels
defaultData = data.default
setChart()
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
function setChart(){
var ctx = document.getElementById("myChart");
var ctx2 = document.getElementById("myChart2");
var myChart = new Chart(ctx2, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Value Contract for Platform',
data: defaultData,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
title:{
display:true,
text:'Count Contract for Every Platform',
fontSize:18,
position:'top'
},
legend:{
display:false,
position:'right',
labels:{
fontColor:'#000'
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
var myChart = new Chart(ctx, {
type: 'polarArea',
data: {
labels: labels,
datasets: [{
label: 'Count Contract for Platform',
data: defaultData,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}
// var ctx = document.getElementById("myChart");
{% endblock %}
</script>
{% block content %}
<div class='row'>
<div class='col-sm-12' url-endpoint='{% url "chartdata" %}'>
<h1>Data Presentation</h1>
<div class=''>
<div class='col-sm-6'>
<canvas id="myChart" width="400" height="400"></canvas>
</div>
<div class='col-sm-6'>
<canvas id="myChart2" width="400" height="400"></canvas>
</div>
</div>
</div>
</div>
{% endblock content %}
Anyway thanks to those who answered my questions

Changing from Highcharts to Highstock - Now Json problems

I had finished my site using highcharts, but as it only could happen... I need to switch to Highstock.
Unfortunately I've got problems to change the code although it's mostly the same... I had 3 line series and now want to switch it to one candlestick and two spline area series.
php file looks like this and the output seems to be fine:
<?php
session_start();
?>
<?php
define('DB_SERVER',"");
define('DB_NAME',"");
define('DB_USER',"");
define('DB_PASSWORD',"");
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db(DB_NAME, $con);
if (isset($_GET["dateParam"])) {
$sql = mysql_query("SELECT unix_timestamp(datetime)*1000 as ts, OpenBid AS open, HighBid AS high, LowBid AS low, CloseBid AS close FROM ger30 WHERE datetime LIKE '".$_GET["dateParam"]."%' ORDER BY datetime");
} else {
$sql = mysql_query("SELECT unix_timestamp(datetime)*1000 as ts, OpenBid AS open, HighBid AS high, LowBid AS low, CloseBid AS close FROM ger30 WHERE DATE(datetime) = CURDATE() ORDER BY datetime");
}
while ($row = mysql_fetch_assoc($sql)) {
if ($row['ts'] == ""){
$row['ts'] = "0";
}
if ($row['open'] == ""){
$row['open'] = 0;
}
if ($row['high'] == ""){
$row['high'] = 0;
}
if ($row['low'] == ""){
$row['low'] = 0;
}
if ($row['close'] == ""){
$row['close'] = 0;
}
$t = $row['ts'];
$o = $row['open'];
$h = $row['high'];
$l = $row['low'];
$c = $row['close'];
$result['data1'][] = array( $t, $o, $h, $l, $c );
}
if (isset($_GET["dateParam"])) {
$sql = mysql_query("SELECT reference FROM kalender WHERE date LIKE '".$_GET["dateParam"]."%'");
} else {
$sql = mysql_query("SELECT reference FROM kalender WHERE DATE(date) = CURDATE()");
}
while ($row = mysql_fetch_assoc($sql)) {
$ref1 = $row['reference'];
}
if (isset($_GET["dateParam"])) {
$sql = mysql_query("SELECT unix_timestamp(datetime)*1000 as ts2, HighBid AS high2, LowBid AS low2 FROM ger30 WHERE DATE(datetime) LIKE DATE('$ref1') ORDER BY datetime");
} else {
$sql = mysql_query("SELECT unix_timestamp(datetime)*1000 as ts2, HighBid AS high2, LowBid AS low2 FROM ger30 WHERE DATE(datetime) = CURDATE() ORDER BY datetime");
}
while ($row = mysql_fetch_assoc($sql)) {
if ($row['ts2'] == ""){
$row['ts2'] = "0";
}
if ($row['high2'] == ""){
$row['high2'] = 0;
}
if ($row['low2'] == ""){
$row['low2'] = 0;
}
$t2 = $row['ts2'];
$h2 = $row['high2'];
$l2 = $row['low2'];
$result['data2'][] = array( $t2, $h2, $l2 );
$result['data3'][] = array( $t2, $h2, $l2 );
}
print json_encode($result, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
so far I recieve 3 correct arrays looking like this:
data1: [1389250800000,9484,9484,9480,9483],[1389250860000,9483,9484,9480,9482]...
data2: [1389078120000,9444,9441],[1389078180000,9444,9442]...
data3: [1389078120000,9444,9441],[1389078180000,9444,9442]
and my java code looks like this:
var options;
$(document).ready(function() {
$.getJSON("testdata2.php", function(json){
options.series[0].data = json['data1'];
chart = new Highcharts.Chart(options);
});
// create the chart
$('#container').highcharts('StockChart', {
options = {
chart:
{
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0, 'rgb(51, 51, 51)'],
[1, 'rgb(16, 16, 16)']
]
},
borderColor: '#666666',
borderWidth: 1,
borderRadius: 0,
zoomType: 'x',
maxZoom: 60000,
renderTo: 'container'
},
rangeSelector : {
enabled: false
},
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0, 'rgb(51, 51, 51)'],
[1, 'rgb(16, 16, 16)']
]
},
xAxis: {
type: 'datetime',
lineColor: '#666666',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
}
},
yAxis: { // first yAxis
alternateGridColor: null,
minorTickInterval: null,
gridLineColor: 'rgba(255, 255, 255, .1)',
minorGridLineColor: 'rgba(255,255,255,0.07)',
lineWidth: 0,
tickWidth: 0,
labels: {
style: {
color: '#999',
fontWeight: 'bold'
}
},
title: {
text: 'DAX',
style: {
color: '#eeeeee'
}
}
},
tooltip: {
backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
stops: [
[0, 'rgba(96, 96, 96, .8)'],
[1, 'rgba(16, 16, 16, .8)']
]
},
borderWidth: 0,
style: {
color: '#FFF'
}
},
title: {
text: 'GER30 Tageschart',
margin: 50,
style: {
fontFamily: 'Verdana',
fontSize: '20px',
fontWeight: 'bold',
color: '#cccccc'
}
},
navigator: {
enabled: false
},
scrollbar: {
enabled: false
},
plotOptions: {
series: {
shadow: true
},
line: {
dataLabels: {
color: '#CCC'
},
marker: {
lineColor: '#333'
}
},
spline: {
marker: {
lineColor: '#333'
}
},
scatter: {
marker: {
lineColor: '#333'
}
},
candlestick: {
lineColor: '#666666'
}
},
series : [{
type : 'candlestick',
name : 'GER30',
data : [],
}]
}
});
});
});
Javascript is updated, to show how it looks like at the moment.
I try to get only one series data work so that I only need to add the others.
The Problem must be somewhere here:
$.getJSON("testdata2.php", function(json){
options.series[0].data = json['data1'];
chart = new Highcharts.Chart(options);
});
If I use
$.getJSON('testdata2.php', function(test) {
instead, and "data: test," in the series part, it works fine.