I want to create a graph that the data are from oracle by using php.
I did not found example that use oracle as a database. Mostly are from mysql.
The data is like this
I have made this code but it's not working.
its show like this
data.php
<?php
header('Content-Type: application/json');
$conn = oci_connect('***', '***', '127.0.0.1/orcl');
$graph=sprintf("SELECT count(pm.packagename) as quantity,pm.packagename
FROM packagemenu pm
INNER JOIN orderdetail od ON od.packageid=pm.packageid
inner join orders o on o.orderid = od.orderid
group by pm.packagename");
$parse=oci_parse($conn,$graph);
oci_execute($parse);
$data=array();
while($row1 = oci_fetch_array($parse)){
$data[]=$row1;
}
print json_encode($data);
?>
bargraph.html
<!DOCTYPE html>
<html>
<head>
<title>ChartJS - BarGraph</title>
<style type="text/css">
#chart-container {
width: 640px;
height: auto;
}
</style>
</head>
<body>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
<!-- javascript -->
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
apps.js
$(document).ready(function(){
$.ajax({
url: "http://localhost/psm/admin/data.php",
method: "GET",
success: function(data) {
console.log(data);
var packagename = [];
var quantity = [];
for(var i in data) {
packagename.push("Packagename " + data[i].packagename);
quantity.push(data[i].quantity);
}
var chartdata = {
labels: packagename,
datasets : [
{
label: 'Package Name',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: quantity
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
Since the data is this:
[{"0":"8","QUANTITY":"8","1":"Set A","PACKAGENAME":"Set A"},{"0":"5","QUANTITY":"5","1":"Set B","PACKAGENAME":"Set B"}]
You have a case sensitivity problem, which makes the array var packagename and quantity empty/undifined.
You need to change:
for(var i in data) {
packagename.push("Packagename " + data[i].packagename);
quantity.push(data[i].quantity);
}
... to ...
for(var i in data) {
packagename.push("Packagename " + data[i].PACKAGENAME);
quantity.push(data[i].QUANTITY);
}
I am not familiar with Chart.js but fixing this so that you are not trying to graph undefined variables is a first step.
Related
index.php - fetches data from mySQL database
<?php
header('Content-Type: application/json');
$conn = mysqli_connect('localhost', 'root', '', 'registration');
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$query = sprintf("SELECT ratingid, variety, quality FROM chartdata ORDER BY ratingid");
$result = mysqli_query($conn, $query);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
mysqli_close($conn);
print json_encode($data);
?>
app.js
$(document).ready(function(){
$.ajax({
url: "http://localhost/mychart4/index.php",
method: "GET",
success: function(data) {
console.log(data);
var rating = [];
var variety = [];
var quality = [];
for(var i in data) {
rating.push(data[i].ratingid);
variety.push(data[i].variety);
quality.push(data[i]).quality);
}
var chartdata = {
labels: rating,
datasets: [
{
label: 'Red',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: variety
},
{
label: 'Blue',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: quality
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: {
barValueSpacing: 20,
title: {
display: true,
text: 'Variety',
fontSize: 20
},
scales: {
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Rating options'
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Amount'
},
ticks: {
beginAtZero: true
}
}]
}
}
});
},
error: function(data) {
console.log(data);
}
});
});
bargaph.html
<!DOCTYPE html>
<html>
<head>
<title>ChartJS - BarGraph</title>
<style type="text/css">
#chart-container {
width: 640px;
height: auto;
}
</style>
</head>
<body>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
<!-- javascript -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
I'm trying to render a grouped bar chart using ChartJS with values from several columns(variety,quality) in my mySQL database. However, the browser does not display anything when I open the HTML file. I'm not sure what the issue might be since the bar chart rendered correctly when I tried it with one column(variety).
This is the output when I print out the JSON array formed from the data:
[{"ratingid":"1","variety":"8","quality":"1"},{"ratingid":"2","variety":"1","quality":"9"},{"ratingid":"3","variety":"1","quality":"0"},{"ratingid":"4","variety":"11","quality":"11"},{"ratingid":"5","variety":"1","quality":"1"}]
There's a very small mistake in the code that needs to be removed.
Current Code:
quality.push(data[i]).quality);
Correction:
quality.push(data[i].quality);
There's just an additional ')' that needs to be removed and it worked...
Bar Chart
Complete working code as below;
<!-- index.php -->
<?php
header('Content-Type: application/json');
$conn = mysqli_connect('localhost', 'root', '', 'registration');
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$query = sprintf("SELECT ratingid, variety, quality FROM chartdata ORDER BY
ratingid");
$result = mysqli_query($conn, $query);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
mysqli_close($conn);
print json_encode($data);
//-- app.js
$(document).ready(function () {
$.ajax({
url: "http://localhost/test/barChart/index.php",
method: "GET",
success: function (data) {
console.log(data);
var rating = [];
var variety = [];
var quality = [];
for (var i in data) {
rating.push(data[i].ratingid);
variety.push(data[i].variety);
quality.push(data[i].quality);
}
var chartdata = {
labels: rating,
datasets: [{
label: 'Red',
backgroundColor: 'rgb(255, 0, 0)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: variety
},
{
label: 'Blue',
backgroundColor: 'rgb(0, 0, 255)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: quality
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: {
barValueSpacing: 20,
title: {
display: true,
text: 'Variety',
fontSize: 20
},
scales: {
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Rating options'
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Amount'
},
ticks: {
beginAtZero: true
}
}]
}
}
});
},
error: function (data) {
console.log(data);
}
});
});
<!-- bargraph.html -->
<!DOCTYPE html>
<html>
<head>
<title>ChartJS - BarGraph</title>
<style type="text/css">
#chart-container {
width: 640px;
height: auto;
}
</style>
</head>
<body>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
<!-- javascript -->
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
Helloi have a problem with chart.js, php and informix database.
first i test the script with easy mysql database and they works good.
but when im using informix database with pdo he show me on chart label undefined.
=> my data.php (for connection to database) :
<?php
header('Content-Type: application/json');
$db=new pdo("informix:host=uccxpub;service=1504;database=db_cra;server=uccxpub_uccx;protocol=onsoctcp;EnableScrollabelCursors=1;client_local=en_US.UTF8;db_locale=en_US.UTF8","uccxwallboard","cisco2016"
) or die("Impossible de se connecter !!!");
$sql0 = sprintf("SELECT * FROM RtCSQsSummary where CSQName = 'BMCE BANK'");
/*$stmt = $db->prepare($sql0);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
*/
$result = $db->query($sql0);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//now print the data
print json_encode($data);
?>
=> the output of data.php :
enter image description here
=> my bargraph.js :
$(document).ready(function(){
$.ajax({
url: "../data.php",
method: "GET",
success: function(data) {
console.log(data);
var startdatetime = [];
var loggedInAgents = [];
for(var i in data) {
startdatetime.push("startdatetime " + data[i].startdatetime);
loggedInAgents.push(data[i].loggedInAgents);
}
var chartdata {
labels: startdatetime,
datasets : [
{
label: 'loggedInAgents',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: loggedInAgents,
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
=> the output :
enter image description here
=> my index.html :
<!DOCTYPE html>
<html>
<head>
<title>ChartJS - BarGraph</title>
<style type="text/css">
#chart-container {
width: 640px;
height: auto;
}
</style>
</head>
<body>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
<!-- javascript -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript" src="js/bargraph.js"></script>
</body>
</html>
!! the bar graph not show me callshandled undefinded ..
test with mysql database :
=> data.php :
<?php
//setting header to json
header('Content-Type: application/json');
//database
define('DB_HOST', '127.0.0.1');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root123');
define('DB_NAME', 'mydb');
//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query = sprintf("SELECT playerid, score FROM score ORDER BY playerid");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data);
=>bargraph.js :
$(document).ready(function(){
$.ajax({
url: "http://localhost/data.php",
method: "GET",
success: function(data) {
console.log(data);
var player = [];
var score = [];
for(var i in data) {
player.push("Player " + data[i].playerid);
score.push(data[i].score);
}
var chartdata = {
labels: player,
datasets : [
{
label: 'Player Score',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: score
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
=> index.html :
<!DOCTYPE html>
<html>
<head>
<title>ChartJS - BarGraph</title>
<style type="text/css">
#chart-container {
width: 640px;
height: auto;
}
</style>
</head>
<body>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
<!-- javascript -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript" src="js/bargraph.js"></script>
</body>
</html>
hes work so fine.
I ran your code (with some minor fixes) on my Linux box. I can display the bar graph with some simple test data from an Informix database:
html page:
informix#irk:/var/www/html# cat test.html
<!DOCTYPE html>
<html>
<head>
<title>ChartJS - BarGraph</title>
<style type="text/css">
#chart-container {
width: 640px;
height: auto;
}
</style>
</head>
<body>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
<!-- javascript -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<script src="http://irk/b.js"></script>
</body>
</html>
informix#irk:/var/www/html#
javascript:
informix#irk:/var/www/html# cat b.js
$(document).ready(function(){
$.ajax({
url: "http://irk/data.php",
method: "GET",
success: function(data) {
var obj=JSON.parse(data);
data=obj;
var startdatetime = [];
var loggedInAgents = [];
for(var i in data) {
startdatetime.push( data[i].STARTDATETIME);
loggedInAgents.push(data[i].LOGGEDINAGENTS);
}
var chartdata = {
labels: startdatetime,
datasets : [
{
label: 'loggedInAgents',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: loggedInAgents
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
informix#irk:/var/www/html#
php script getting the data from Informix:
informix#irk:/var/www/html# cat data.php
<?php
$db=new pdo("informix:database=enusutf8;server=irk1210;CLIENT_LOCALE=en_US.UTF8;DB_LOCALE=en_US.UTF8","informix","testpwd") or die("Impossible de se connecter !!!");
$sql0 = sprintf("SELECT * FROM RtCSQsSummary where CSQName = 'BMCE BANK'");
$result = $db->query($sql0);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
print json_encode($data);
?>
informix#irk:/var/www/html#
In addition to the uppercase/lowercase mentioned before, the JSON data the JS function gets
has to be parse before it can be used. Otherwise you will get "undefied" values in the 'for(var i in data)' loop, no matter what case you used.
I am trying to use chartJs to draw a bar chart on my laravel project but I have been getting this error -
"Failed to create chart: can't acquire context from the given item".
I have tried debugging and I think everything looks okay.
This is my JS file
$(document).ready(function () {
$.ajax({
url: "{{url('properties','totalTaxPaidByLga')}}",
method: "GET",
success: function(data) {
console.log(data);
var player = [];
var score = [];
for(var i in data) {
player.push("Player " + data[i].playerid);
score.push(data[i].score);
}
var chartdata = {
labels: player,
datasets : [
{
label: 'Player Score',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: score
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
This is my blade file
<div id="chart-container">
<canvas id="mycanvas"> </canvas>
<p>Hi</p>
</div>
This is my controller
public function totalTaxPaidByLga(){
$query = DB::select("select SUM(a.settlement_amount) as totalTaxPaid, d.local_name from settlements as a, assessments as b,
property_details as c, locals as d
where a.assessment_ref = b.assessment_ref and
b.property_id = c.id and
c.lga_id = d.local_id
GROUP BY d.local_id");
foreach ($query as $row) {
$data[] = $row;
}
print json_encode($data);
}
Hello :) (I'm novice and I learn on the job),
I work with Chart.js, jQuery, PostgreSQL
Currently I have a bar chart directly linked to PostgreSQL database.
I'd like to add a dropdown to allow the user to select a "zone", which would dynamically update the chart.
Each "zone" has different variables: population, salaries (number of employees in english), etc.
Here is the PHP
<?php
$dbconn = pg_connect("")
or die('Erreur de connexion'.pg_last_error());
$query = "SELECT id, zone_nom, zone_pop, zone_salaries FROM table";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
$array = array();
while ($row = pg_fetch_array($result, null, PGSQL_ASSOC)) {
$array[] = $row;
}
$data=json_encode($array);
echo $data;
pg_free_result($result);
pg_close($dbconn);
?>
I get the following array
[{"id":"1","zone_nom":"test ","zone_pop":"36105","zone_salaries":"15279"},{...],{...}]
Then I generate a dropdown dynamically populated by my table
But I'm stuck on how to pass the selected values in the chart (and then make sure the chart gets refreshed depending on the choice in the dropdown)
<html>
<head>
<title>Liste déroulante dynamique</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v1.0.3/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet/v1.0.3/leaflet-src.js"></script>
<script type="text/javascript">
function Zone() {
$('#zone-select').empty();
$('#zone-select').append("<option>Chargement</option>");
$.ajax({
type: "POST",
url: "http://localhost/data.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
$('#zone-select').empty();
$('#zone-select').append("<option value='0'>-- Select zone --</option>");
$.each(data,function(i, item){
$('#zone-select').append('<option value='+data[i].zone_pop+'>'+data[i].zone_nom+'</option>');
});
$("#zone-select").change(function(){
var value = $("#zone-select option:selected").val(); // Value of selected option
console.log('Value: '+value);
});
// How to link the dropdown and the chart ?
var zoneNom = [];
var zonePop = [];
for(var i in data) {
zoneNom.push(data[i].zone_nom);
zonePop.push(data[i].zone_pop);
zoneSalaries.push(data[i].zone_salaries)
}
var chartdata = {
labels: zoneNom,
datasets : [
{
label: 'Population',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: zonePop
},
{
label: 'Salaries',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: zoneSalaries
}
]
};
var option = {};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: option
});
var myBarChart;
},
complete: function(){
}
});
}
$(document).ready(function(){
Zone();
});
</script>
</head>
<body>
<select id="zone-select"></select>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
</body>
</html>
The value of the choice is returned
$("#zone-select").change(function(){
var value = $("#zone-select option:selected").val(); // Value of selected option
console.log('Value: '+value);
});
I am looking for but I can not find the solution for now (probably not very complicated)
Thank you in advance for your help
You could accomplish this using the following on change event handler function for your dropdown menu ...
$("#zone-select").change(function() {
var nom = $("#zone-select option:selected").text(); // name of selected option
var index = zoneNom.indexOf(nom);
var new_labels = [zoneNom[index]];
var new_data1 = [zonePop[index]];
var new_data2 = [zoneSalaries[index]];
barGraph.data.labels = new_labels;
barGraph.data.datasets[0].data = new_data1;
barGraph.data.datasets[1].data = new_data2;
barGraph.update(); // update chart
});
and, if you wish to select the first option by default, use ...
$("#zone-select").val(zonePop[0]).trigger('change');
working example
function Zone() {
$('#zone-select').empty();
$('#zone-select').append("<option>Chargement</option>");
$.ajax({
type: "GET",
url: "https://istack.000webhostapp.com/json/t9.json",
dataType: "json",
success: function(data) {
//console.log(data)
$('#zone-select').empty();
$('#zone-select').append("<option value='0'>-- Select zone --</option>");
$.each(data, function(i, item) {
$('#zone-select').append('<option value=' + data[i].zone_pop + '>' + data[i].zone_nom + '</option>');
});
$("#zone-select").change(function() {
var nom = $("#zone-select option:selected").text(); // name of selected option
var index = zoneNom.indexOf(nom);
var new_labels = [zoneNom[index]];
var new_data1 = [zonePop[index]];
var new_data2 = [zoneSalaries[index]];
barGraph.data.labels = new_labels;
barGraph.data.datasets[0].data = new_data1;
barGraph.data.datasets[1].data = new_data2;
barGraph.update(); // update chart
});
var zoneNom = [];
var zonePop = [];
var zoneSalaries = [];
for (var i in data) {
zoneNom.push(data[i].zone_nom);
zonePop.push(data[i].zone_pop);
zoneSalaries.push(data[i].zone_salaries)
}
var chartdata = {
labels: zoneNom,
datasets: [{
label: 'Population',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: zonePop
}, {
label: 'Salaries',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: zoneSalaries
}]
};
var option = {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: option
});
var myBarChart;
$("#zone-select").val(zonePop[0]).trigger('change'); // select first option
},
complete: function() {}
});
}
$(document).ready(function() {
Zone();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<select id="zone-select"></select>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
I am new to highcharts. I can get the title to show up, but for some reason the x and y axis data won't come up. I am getting my data from a database with php, along with encoding it with JSON. Here is my HTML:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'bar'
},
title: {
text: 'TCP Upload Speed Averages for Los Angeles County in 2012',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
min:0,
title: {
text: 'TCP Upload Averages'
},
labels: {
overflow: 'justify'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
},
series: {
stacking:'percent'
}
},
series: []
};
$.getJSON("2012Data.php", function(json) {
options.xAxis.categories = json[0]['data'];//xAxis: {categories: []}
options.series[0] = json[1];
//chart = new Highcharts.Chart(options);
});
chart = new Highcharts.Chart(options);
});
</script>
<script src="highstock.js" ></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<div id="container" style="width: 600px; height: 400px; margin: 0 auto"></div>
</body>
Here is my JSON data from the php:
[{"name":"Providers","data":["AT&T","Sprint","T-Mobile","Verizon"]},{"name":"Averages","data":[972.03790849673,679.63696969697,992.06606060606,4520.2101851852]}]
Thanks for the help!
Your chart displays only the title because no data is loaded. And although your AJAX-call might be working: setting the options in its callback is too late, since the callback will most likely be invoked only after the chart has been created.
Does it work for you if you uncomment the line //chart = new Highcharts.Chart(options); in the getJSON callback (and of course remove the other Highcharts constructor call two lines down)?
However, the more idiomatic way to load data is to create a callback for the load-Event of the chart, fire your AJAX-Request and then insert the data in the already created chart. I have created a JSFiddle for you where i simulate the call to your php-script via a timeout. You should get your chart working by using the following load-callback:
chart: {
events: {
load: function(event) {
var chart = event.target;
$.getJSON("2012Data.php", function(json) {
var xAxis = chart.xAxis[0];
xAxis.setCategories(json[0]['data']);
chart.addSeries(json[1]);
});
}
}
}