I am working on Highcharts using PHP/MYSQL. Data is showing properly in each chart but I tried to change one chart to ajax call in order to reduce page load.
I am generating multiple series data from PHP and displaying them back in the required format but data is not showing(I alerted the data it's coming).
Below is the code of ajax call:
function project_wise_lab(from_date, to_date) {
$.ajax({
type: "POST",
url: 'dashboard/project_wise_labtest',
data: {
from_dte: from_date,
to_dte: to_date
},
success: function(response) {
Highcharts.chart('subcontainer7', {
chart: {
type: 'line',
height: 230,
},
credits: {
enabled: false
},
title: {
text: null
},
xAxis: {
categories: ['Oct 2020', 'Nov 2020', 'Dec 2020', 'Jan 2021', 'Feb 2021', 'Mar 2021', 'Apr 2021', 'May 2021']
},
yAxis: {
min: 0,
title: {
// text: 'Total fruit consumption'
},
stackLabels: {
enabled: false,
style: {
fontWeight: 'bold',
color: ( // theme
Highcharts.defaultOptions.title.style &&
Highcharts.defaultOptions.title.style.color
) || 'gray'
}
}
},
legend: {
align: 'center',
verticalAlign: 'bottom',
backgroundColor: Highcharts.defaultOptions.legend.backgroundColor || 'white',
borderColor: '#CCC',
// borderWidth: 1,
shadow: false
},
tooltip: {
/* headerFormat: '<b>{point.x}</b><br/>',
pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
*/
},
plotOptions: {
column: {
stacking: 'normal',
dataLabels: {
// enabled: true
}
}
},
colors: [
'#4a7fbb',
'#be4c48',
'#97b954',
'#7d6096'
],
series: response
});
console.log(response);
},
error: function(xhr, status, error) {
console.error(xhr);
}
});
}
I have alerted the response and the data is showing in the below format:
{ name : 'FKI',data : [10591,10576,9309,8422,9586,11171,9327,9384] },{ name : 'FKR',data : [4740,3105,2690,3598,3686,4930,3711,3859] },{ name : 'FHR',data : [17190,12757,10837,11944,14083,15748,12544,12494] },{ name : 'FUL',data : [1308,937,1002,1086,1452,1419,1248,1362] },{ name : 'FSW',data : [9535,9102,8689,8420,9941,10915,7273,6930] },{ name : 'FWP',data : [47437,42198,43012,44979,47377,55400,46520,41682] },{ name : 'FGR',data : [2112,1366,1619,1664,2387,2355,1633,1215] }
New Response after update:
[{"name":"FKI","data":{"01-OCT-20":"10591","01-NOV-20":"10576","01-DEC-20":"9309","01-JAN-21":"8422","01-FEB-21":"9586","01-MAR-21":"11171","01-APR-21":"9332","01-MAY-21":"9384"}},{"name":"FKR","data":{"01-OCT-20":"4740","01-NOV-20":"3105","01-DEC-20":"2690","01-JAN-21":"3598","01-FEB-21":"3686","01-MAR-21":"4930","01-APR-21":"3711","01-MAY-21":"3859"}},{"name":"FHR","data":{"01-OCT-20":"17190","01-NOV-20":"12757","01-DEC-20":"10837","01-JAN-21":"11944","01-FEB-21":"14083","01-MAR-21":"15748","01-APR-21":"12544","01-MAY-21":"12494"}},{"name":"FUL","data":{"01-OCT-20":"1308","01-NOV-20":"937","01-DEC-20":"1002","01-JAN-21":"1086","01-FEB-21":"1452","01-MAR-21":"1419","01-APR-21":"1248","01-MAY-21":"1362"}},{"name":"FSW","data":{"01-OCT-20":"9535","01-NOV-20":"9102","01-DEC-20":"8689","01-JAN-21":"8420","01-FEB-21":"9941","01-MAR-21":"10915","01-APR-21":"7273","01-MAY-21":"6930"}},{"name":"FHP","data":{"01-OCT-20":"47437","01-NOV-20":"42198","01-DEC-20":"43012","01-JAN-21":"44979","01-FEB-21":"47377","01-MAR-21":"55400","01-APR-21":"46520","01-MAY-21":"41682"}},{"name":"FGR","data":{"01-OCT-20":"2112","01-NOV-20":"1366","01-DEC-20":"1619","01-JAN-21":"1664","01-FEB-21":"2387","01-MAR-21":"2355","01-APR-21":"1633","01-MAY-21":"1215"}}]
The chart is showing empty, kindly help and let me know to get the issue resolve?
Thanks
You appear to have two problems...
jQuery is interpreting your response as plain text (a string) where Highcharts expects actual JS objects
Your response is not valid JSON so you can't interpret it as such on the client-side. Rule #1 when creating JSON responses is... never roll your own JSON.
I recommend getting PHP to generate valid JSON and respond with the correct Content-type
// Ensure jQuery (or any consumer) knows the response is JSON
header("Content-type: application/json");
// Create a data structure representing the series data
$data = [];
foreach ($project as $key => $value) {
$data[] = [
"name" => $key,
"data" => array_values($value) // you just want the values here, not the keys
];
}
// Respond with JSON
echo json_encode($data);
exit;
Then in your client-side code, you can simply use
series: response
as response will now be a valid JS array
You can also make sure jQuery treats the response as JSON by adding
dataType: "json",
to your $.ajax() options but with the right Content-type response header, jQuery should not need this.
Just an FYI, alert() is terrible for viewing data. The best option would be to use your browser's debugger. The second best option is to use console.log()
Related
Firstly I apologise, I am not a programmer (but I am learning - slowly). I am interested in graphs for Horticultural applications. I have a database that gets data from sensors on an hourly basis and the query grabs the last 12 to 48 readings, according to the select statement. With help from your forum, I have created 3 files that together extract the data from MySQL to plot a graph with multiple series of: Timestamp (with various options for display), temperature and humidity.
I based my work on this example in fiddle https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/line-basic which uses data provided 'in the script' but after three weeks I can't inject the data from JSON
The first of my files makes the MySQL db connection, the second file extracts and formats the data into JSON data and the third is supposed to create the graph but doesn't :-(.
this is what is produced with a series label for each row, rather than a line for each series.
Can you help me? I would like a line graphs showing temperature and humidity. Time/date along the bottom x-axis, the left y-axis temperature in degrees and a right-hand y-axis showing percentage humidity. Am I asking too much?
Finally can I please request no Ajax, or other "stuff" other than php, html, JSON, and javascripts if possible?
Any help on formatting my question would be much appreciated :-)
<?php $json_data = include ('nw_database02.php');?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Line Graph</title>
</head>
<body>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<div id="container"></div>
<script type="text/javascript">
Highcharts.chart('container', {
title: {
text: 'Temperature and Humidity'
},
subtitle: {
text: 'Source: Greenhouse1'
},
yAxis: {
title: {
text: 'Temperature'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 2010
}
},
series: <?= $json_data?> ,
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
</script>
</body>
</html>
...
If I echo the $json_data I get this type of result, but bear in mind it is dynamic data and changes every hour so it must be read from json_data every time the page is accessed:
[{"Timestamp":"10:04 02/01/21","temperature":"5","humidity":"66"},{"Timestamp":"10:19 02/01/21","temperature":"6","humidity":"65"},{"Timestamp":"10:35 02/01/21","temperature":"6","humidity":"64"},{"Timestamp":"10:50 02/01/21","temperature":"6","humidity":"64"},{"Timestamp":"11:06 02/01/21","temperature":"6","humidity":"64"},{"Timestamp":"11:21 02/01/21","temperature":"7","humidity":"63"},{"Timestamp":"11:34 02/01/21","temperature":"10","humidity":"66"},{"Timestamp":"04:21 02/01/21","temperature":"15","humidity":"64"},{"Timestamp":"04:36 02/01/21","temperature":"16","humidity":"61"},{"Timestamp":"04:51 02/01/21","temperature":"15","humidity":"59"},{"Timestamp":"05:07 02/01/21","temperature":"15","humidity":"60"},{"Timestamp":"05:22 02/01/21","temperature":"14","humidity":"61"}]
You need to format your data to the series structure required by Highcharts. The rest of the requirements are achievable by using chart options - please check xAxis and yAxis properties in API.
var data = <?= $json_data?>
var series = [{
name: "temperature",
data: []
},
{
name: "humidity",
data: [],
yAxis: 1
}
];
data.forEach(function(dataEl) {
series[0].data.push([
new Date(dataEl.Timestamp).getTime(),
Number(dataEl.temperature)
]);
series[1].data.push([
new Date(dataEl.Timestamp).getTime(),
Number(dataEl.humidity)
]);
});
Highcharts.chart('container', {
series: series,
yAxis: [{
title: {
text: 'temperature'
}
},
{
title: {
text: 'humidity'
},
opposite: true
}
],
xAxis: {
type: 'datetime'
}
});
Live demo: http://jsfiddle.net/BlackLabel/aw95vek6/
API Reference: https://api.highcharts.com/highcharts/series.line.data
you can achive with below code but when you choosing chart first know the purpose and create json data accroding to the series use apexcharts for free
<script type="text/javascript">
var data=[{"Timestamp":"10:04 02/01/21","temperature":"5","humidity":"66"},{"Timestamp":"10:19 02/01/21","temperature":"6","humidity":"65"},{"Timestamp":"10:35 02/01/21","temperature":"6","humidity":"64"},{"Timestamp":"10:50 02/01/21","temperature":"6","humidity":"64"},{"Timestamp":"11:06 02/01/21","temperature":"6","humidity":"64"},{"Timestamp":"11:21 02/01/21","temperature":"7","humidity":"63"},{"Timestamp":"11:34 02/01/21","temperature":"10","humidity":"66"},{"Timestamp":"04:21 02/01/21","temperature":"15","humidity":"64"},{"Timestamp":"04:36 02/01/21","temperature":"16","humidity":"61"},{"Timestamp":"04:51 02/01/21","temperature":"15","humidity":"59"},{"Timestamp":"05:07 02/01/21","temperature":"15","humidity":"60"},{"Timestamp":"05:22 02/01/21","temperature":"14","humidity":"61"}];
console.log(data);
var timestamp=[];
var temperature=[];
var humidity=[];
$.each(data, function(i, item) {
console.log(data[i]);
timestamp.push(data[i].Timestamp);
temperature.push(data[i].temperature);
humidity.push(data[i].humidity);
});
Highcharts.chart('container', {
title: {
text: 'Solar Employment Growth by Sector, 2010-2016'
},
subtitle: {
text: 'Source: thesolarfoundation.com'
},
yAxis: {
title: {
text: 'Number of Employees'
}
},
xAxis: {
categories: timestamp,
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
pointStart: 2010
}
},
series: [{
name: 'temperature',
data: temperature
}, {
name: 'humidity',
data: humidity
}],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
</script>
Within my Laravel project I am implementing the chart.js library trying to visualize a bar graph.
Which should show all work orders in finished status that were assigned to users with the operator role.
When you want to graph, simply no data is displayed, it is an empty graph.
This is my ReportController controller with this method public function getChart () I do my query
public function getChart(Request $request)
{
$_orders = DB::table('users')
->join('orders','orders.user_id','=','users.id')
->join('model_has_roles', 'users.id', '=', 'model_has_roles.model_id')
->select('users.id','users.name', DB::raw('COUNT(orders.id) as orders_by_user'), 'model_has_roles.role_id as rol')
->where('model_has_roles.role_id', '2');
$_orders->groupBy('orders.user_id', 'users.id', 'users.name', 'model_has_roles.role_id');
$orders=$_orders->get();
return ['orders' => $orders];
}
This is the result of my query: as it is observed I have what I need username and the number of orders completed per user.
{
"orders": [
{
"id": 4,
"name": "Luis",
"orders_by_user": 2,
"rol": 2
},
{
"id": 6,
"name": "Jose",
"orders_by_user": 1,
"rol": 2
},
{
"id": 7,
"name": "Miguel",
"orders_by_user": 1,
"rol": 2
}
]
}
Here is an important question: is the JSON structure returned by my query correct? With this result can I graph?
This is my report.js file for the graph:
With the renderChart() method:
I make the graph, through the data obtained in my ajax call.
With the getChartData () method:
I make my ajax call.
function renderChart(data, labels) {
var ctx = document.getElementById("orders").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'ordenes',
data: data,
borderColor: 'rgba(75, 192, 192, 1)',
backgroundColor: 'rgba(75, 192, 192, 0.2)',
borderWidth: 1,
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
title: {
display: true,
text: "Ordenes en estado terminado"
},
}
});
}
function getChartData() {
$.ajax({
url: '/admin/reports/getChart',
type: 'GET',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
dataType: 'json',
success: function (data) {
// console.log(data);
var data = [];
var labels = [];
for (var i in data) {
data.push(data[i].orders_by_user);
labels.push(data[i].name);
}
renderChart(data, labels);
},
error: function (data) {
console.log(data);
}
});
}
$("#renderBtn").click(
function () {
getChartData();
}
);
In other words I am looking to optimize my query using eloquent, so that it returns a valid JSON response for chart.js.
Dump those data obtained through an ajax call and draw
Could you help me find and solve my error?
UPDATED 1
Just in case if any error arises change my for: for (var i in data) to this: for (var i in response)
So it looks like this:
for (var i in response) {
data.push(response[i].orders_by_user);
labels.push(response[i].name);
}
I think that I am not accessing correctly the data that I get from my query to later graph.
In the console I see the following information:
{orders: Array(3)}
orders: Array(3)
0: {id: 4, name: "Luis", orders_by_user: 2, rol: 2}
1: {id: 6, name: "Jose", orders_by_user: 1, rol: 2}
2: {id: 7, name: "Miguel", orders_by_user: 1, rol: 2}
length: 3
__proto__: Array(0)
__proto__: Object
Orders is my array, so how can I just access orders_by_user and name and correctly pass it to my data.push and labels.push
try something like this but it doesn't work:
data.push(response[i].orders.orders_by_user);
labels.push(response[i].orders.name);
Free jqGrid uses data in the following JSON name:value pairs format:
var data = {
"page": "1",
"records": "3",
"rows": [
{ "DataID": "1", "DataDesc": "Test 1", "DataTitle": "Test 1" }
]
};
I have the following in the PHP script:
$i=0;
while ($row = mysql_fetch_assoc($result)) {
$data->rows[$i]['cell']=array($row);
$i++;
}
print json_encode($data);
Which returns:
{"rows":[{"cell":[{"user_id":"00082563","first_name":"Peter","case_title":"Male with STI (urethritis)","case_started":"2017-06-02 10:52:10"}]}]}
Which looks to be OK. However, with the JSON parts of the code below, the grid doesn't display at all.
function loadFirstGrid() {
$("#FirstGrid").jqGrid({
url: "scripts/json_test.php?user=" + user,
dataType: "json",
mtype: "GET",
postData: {
json: JSON.stringify(data)
},
colModel: [{
name: "user_id",
label: "User ID",
width: 120
},
{
name: "first_name",
label: "Name",
width: 400
},
{
name: "case_title",
label: "Case Title",
width: 500
},
{
name: "case_started",
label: "Case Started",
width: 200
},
],
emtyrecords: "Nothing to display",
viewrecords: true,
sortable: true,
shrinkToFit: false,
autowidth: true,
caption: 'First Grid'
});
}
But if I remove the postData part to have the following, the grid displays, but of course no data.
function loadFirstGrid() {
$("#FirstGrid").jqGrid({
url: "scripts/json_test.php?user=" + user,
dataType: "json",
mtype: "GET",
colModel: [{...
Any ideas?
OK, finally worked through this and got it working with this
function loadFirstGrid() {
$("#FirstGrid").jqGrid({
url: "scripts/json_test.php?user=" + user,
dataType: "json",
mtype: "GET",
colModel: [
{name: "user_id", label:"User ID", width: 120},
{name: "first_name", label:"Name", width: 400},
{name: "case_title", label:"Case Title", width: 500},
{name: "case_started", label:"Case Started", width: 200},
],
emtyrecords: "Nothing to display",
viewrecords: true,
sortable: true,
shrinkToFit: false,
autowidth: true,
caption: 'First Grid',
});
}
To get the correct format JSON for jqGrid:
{"page":"1","total":"1","records":"1","rows":[{"user_id":"00082563","first_name":"Peter","case_title":"Male with STI (urethritis)","case_started":"2017-06-02 10:52:10"}]}
I used the following PHP script:
$page = '1';
$total_pages = '1';
$count = '1';
$data = (object) array('page' => $page, 'total' => $total_pages, 'records' =>$count, 'rows' => "");
$data->page = $page;
$data->total = $total_pages;
$data->records = $count;
$i=0;
while ($row = mysql_fetch_assoc($result)) {
$data->rows=array($row);
$i++;
}
print json_encode($data);
?>
(NOTE: I don't care about the number of pages, total_pages and count as my grids will only ever have one primary record and multiple subgrids with only one record). So hope this helps someone; there is not much in the documentation or examples that describes how to do this with Free jqGrid ;-(
First of all JavaScript is case sensitive language and jqGrid will ignore parameter dataType: "json". You should fix it to datatype: "json".
Seconds, you use exotic format of the JSON data:
{
"rows": [{
"cell": {
"user_id": "00082563",
"first_name": "Peter",
"case_title": "Male with STI (urethritis)",
"case_started": "2017-06-02 10:52:10"
}
}]
}
instead of
{
"rows": [ {
"user_id": "00082563",
"first_name": "Peter",
"case_title": "Male with STI (urethritis)",
"case_started": "2017-06-02 10:52:10"
}]
}
or
[ {
"user_id": "00082563",
"first_name": "Peter",
"case_title": "Male with STI (urethritis)",
"case_started": "2017-06-02 10:52:10"
}]
You don't use loadonce: true and it's unclear, whether you plan to implement server side paging, sorting and filtering of data or you want to return all the data at once and jqGrid should use client side paging, sorting and filtering.
Finally, you should use name properties of colModel corresponds to the properties of user_id. It's very important to understand, that jqGrid have to assign unique id to every row of the grid (see here). Thus you have to inform jqGrid, which property contains rowid. You can use either jsonReader: { id: "user_id" } or to include property key: true in the column user_id.
The demo https://jsfiddle.net/OlegKi/qgrwymuu/1/ contains an example of described above modifications. It uses Echo service of JSFiddle to simulate server, which responses with some JSON data.
Good day,
I'm pretty new in extjs 5 and mvvm. I want to make an ajax request in order to display a treepanel with datas caught with a php.
Here is my store
Ext.define('MyApp.store.servicesStore', {
extend: 'Ext.data.TreeStore',
// alias: 'store.servicesStore',
storeId : 'servicesStore',
model : 'MyApp.model.servicesModel',
proxy: {
type: 'ajax',
url: 'app/store/data/GetServices.php'
},
root: {
text: 'Events',
id: 'root'
},
autoLoad: true,
folderSort: true
});
I've seen that a "success" can resolve that issue but I don't need a succes as it's only displayed in a treePanel
Ext.define('MyApp.view.tabServices.servicesTab', {
extend: 'Ext.tree.Panel',
xtype: 'servicesTab',
layout: {
type: 'border'
},
useArrows: true,
rootVisible: false,
store: {type: 'servicesStore'},
forceFit: true,
columns: [{
xtype: 'treecolumn',
dataIndex: 'text',
width: 600
}, {
dataIndex: 'mbt',
cls: 'mbtcss',
width: 80
}, {
dataIndex: 'bt',
cls: 'btcss',
width: 75
}, {
dataIndex: 'details', // port separated from rest
width: 60
}, {
dataIndex: 'code',
width: 80
}]
});
So, when I launch my app, the "You're trying to decode an invalid JSON String" appears, how can I do to make it understand that I actually use a php file?
More precisely, that code is working in extjs 3.4
To run the PHP code which did work under ExtJS 4 you must either modify your PHP to return the data in JSON format. Or otherwise you set your "enable compatibility" to version 4.
See "Enabling Compatibility" under http://docs.sencha.com/extjs/5.0/whats_new/5.0/extjs_upgrade_guide.html#Enabling_Compatibility.
compatibility: {
ext: '4.2'
}
This is my first post, apologies if I've asked a question a number of people have already done so. I don't see the answer I need in other posts.
I'm using Flot Charts and have a SQL Server db, I've got a php file that will connect to the db and return all the values within the sql in an array.
<?php
$server = "XXXX";
$database = "XXXX";
$user = "ReportsUser";
$pwd = "ReportsUser";
$cnn = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $pwd);
if(!$cnn)
{
echo "error in connecting";
}
$sql = odbc_exec($cnn, "
SELECT Months
,Referrals
,ProjectedVol
FROM mis.ReferralsBudgetvsActual
WHERE Months <= MONTH(GETDATE())
");
while($result = odbc_fetch_array($sql))
{
$allreferrals[] = array($result['Months'],$result['Referrals'],$result['ProjectedVol']);
}
echo json_encode(($allreferrals), JSON_NUMERIC_CHECK);
exit;
?>
This works well and produces the array as below
[[1,5981,7465],[2,5473,6962],[3,4974,7391],[4,5731,6985],[5,5891,7080],[6,5168,7136],[7,5551,7543],[8,4427,7242],[9,4617,7204],[10,4807,7642]]
Now, when it all comes together in the jquery file, this is where I end up getting stuck. I don't see where it pulls any other columns back apart from the first data column, how can this be done?
// document ready function
$(document).ready(function() {
var chartColours = ['#88bbc8', '#ed7a53', '#9FC569', '#bbdce3', '#9a3b1b', '#5a8022', '#2c7282'];
// function for refreshing shiftstats chart
make_chart();
function make_chart() {
$.ajax({
cache: 'false',
type: 'GET',
dataType: 'json',
url: "test.php",
success: function(data) {
var d1 = data;
var d2 = data;
//define placeholder class
var placeholder = $(".shifts-chart");
//graph options
var options = {
grid: {
show: true,
aboveData: true,
color: "#3f3f3f" ,
labelMargin: 5,
axisMargin: 0,
borderWidth: 0,
borderColor:null,
minBorderMargin: 5 ,
clickable: true,
hoverable: true,
autoHighlight: true,
mouseActiveRadius: 20
},
series: {
grow: {
active: false,
stepMode: "linear",
steps: 50,
stepDelay: true
},
lines: {
show: true,
fill: false,
lineWidth: 4,
steps: false
},
points: {
show:true,
radius: 5,
symbol: "circle",
fill: true,
borderColor: "#fff"
}
},
legend: {
position: "ne",
margin: [0,-25],
noColumns: 0,
labelBoxBorderColor: null,
labelFormatter: function(label, series) {
// just add some space to labes
return label+' ';
}
},
yaxis: { min: 0 },
xaxis: {ticks:11, tickDecimals: 0},
colors: chartColours,
shadowSize:1,
tooltip: true, //activate tooltip
tooltipOpts: {
content: "%s : %y.0",
shifts: {
x: -30,
y: -50
}
}
};
$.plot(placeholder,
[{
label: "Referrals",
data: d1,
lines: {fillColor: "#f2f7f9"},
points: {fillColor: "#88bbc8"}
},
{
label: "ProjectedVol",
data: d2,
lines: {fillColor: "#f2f7f9"},
points: {fillColor: "#88bbc8"}
}
], options);
}
});
}
});
Thanks
You'll need to change your php array creation to properly format the data into two series:
$d1 = array();
$d2 = array();
while($result = odbc_fetch_array($sql))
{
array_push($d1, array($result['Months'], $result['Referrals']));
array_push($d2, array($result['Months'], $result['ProjectedVol']));
}
$allreferrals = array($d1, $d2);
echo json_encode(($allreferrals), JSON_NUMERIC_CHECK);
This should return it as an array of arrays:
[
[[1,5981],[2,5473],[3,4974],[4,5731],[5,5891],[6,5168],[7,5551],[8,4427],[9,4617,7204],[10,4807]],
[[1,7465],[2,6962],[3,7391],[4,6985],[5,7080],[6,7136],[7,7543],[8,7242],[9,7204],[10,7642]]
]
(Hopefully I have the syntax correct, I'm not a fan of php)
Update from comment
If you are returning a slew of series, you might be better returning an associative array from PHP:
$allreferrals = array('ref' => array(), 'projVol'=> array());
while($result = odbc_fetch_array($sql))
{
array_push($allreferrals['ref'], array($result['Months'], $result['Referrals']));
array_push($allreferrals['projVol'], array($result['Months'], $result['ProjectedVol']));
}
echo json_encode(($allreferrals), JSON_NUMERIC_CHECK);
Then back in the javascript:
$.plot(placeholder,
[{
label: "Referrals",
data: data["ref"]
},
{
label: "ProjectedVol",
data: data["projVol"]
}],
options);