JSON Output File Format - php

I am using Canvasjs Charts to do my graphing from PHP / MySQL. Everything works as expected except for the creating of my JSON file.
Canvasjs requires the JSON file to look as follow:
callback({
"dps":
[{"division":"Xaxis VALUE","units":Yaxis VALUE}]
})
However, when creating my JSON file it is
[{"division":"Xaxis VALUE","units":Yaxis VALUE}]
All I want to know is how do I add the opening tag and closing tag in the sjon file from my script.
Here is the last part of my code that creates the JSON file:
$output_data= array();
while($row = mysqli_fetch_array($result))
{
$output_data[] = array(
'division' => $row["division"],
'units' => $row["units"]
);
}
return json_encode($output_data, JSON_NUMERIC_CHECK);
echo json_encode($output_data, JSON_NUMERIC_CHECK);
}
$file_name = 'myresult2'.'.json';
if(file_put_contents($file_name, get_data()))
{
echo $file_name. 'file created';
}
else
{
echo 'Error';
}
?>
Additional Data:
This is the code that generates the graph.
<script>
var chart = null;
var dataPoints = [];
window.onload = function() {
chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light",
title: {
text: "Graph Header"
},
axisY: {
title: "% Verified",
titleFontSize: 12,
labelFontSize: 12,
valueFormatString: "#.##%"
},
axisX: {
title: "Division",
titleFontSize: 12,
labelFontSize: 12
},
data: [{
type: "column",
yValueFormatString: "#.##%",
dataPoints: dataPoints
}]
});
$.getJSON("myresult.json?callback=?", callback);
}
function callback(data) {
for (var i = 0; i < data.dps.length; i++) {
dataPoints.push({
label: data.dps[i].division,
y: data.dps[i].units
});
}
chart.render();
}
</script>

Please try
// change this
$output_data[] = array(
// to this
$output_data['dps'][] = array(

What you need to do is enclose you created array in a new array with a key named dps.
So after your while loop you should do something like this
$json_data['dps']=$output_data;
return json_encode($json_data, JSON_NUMERIC_CHECK);

Related

Line Chart using Chart js with time data

I am creating a line chart using chartJs by passing date at X-Axis and time (mm:ss) at Y-Axis. I am not sure how to use chartJs with time values.I tried different solutions from stack but none works in my case.
Here is json file
{"label":["08-Aug-2019","11-Aug-2019","22-Aug-2019","25-Aug-2019"],"time":["1:08","1:44","2:27","1:02"],"chart_data":"{\"label\":[\"08-Aug-2019\",\"11-Aug-2019\",\"22-Aug-2019\",\"25-Aug-2019\"],\"time\":[\"1:08\",\"1:44\",\"2:27\",\"1:02\"]}"}
Here is what i am trying to code
<div id="time_chart"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script>
<script>
let sData = JSON.parse('<?php echo $chart_data; ?>');
let time_ctx = $("#time-chart");
//Line Chart
var time_data = {
labels: sData.label,
datasets: [
{
label: sData.label,
data: sData.time
}
]
};
//options line chart
var time_options = {
responsive: true,
title: {
display: false
},
legend: {
display: false
},
scales: {
yAxes: [{
type: 'time',
time: {
parser: 'm:s',
unit: 'minute',
unitStepSize: 2,
min: '0:0',
max: '30:00',
displayFormats: {
'seconds': 'm.s'
}
},
ticks: {
callback: function(value, index, values) {
//Ticks reverse does not work with time axes so we have to revert in this callback
if (values[values.length - index] != undefined) {
return moment(values[values.length - index].value).format('m.s');
}
}
}
}]
}
};
var chart2 = new Chart(time_ctx, {
type: "line",
data: time_data,
options: time_options
});
</script>
This is what I am getting with this code:
Although I didn't manage to use a time axis for both the x- and y-axes, I managed to create a workaround with a timed x-axis and a linear y-axis.
I parse your time and return the time in seconds (integer). I use this value to display your time and change the format back to mm:ss.
I hope this is what you wanted. I'm not sure you want the axes this way (because in your code you use the y-axis as type "time").
PS: My first post, please feel free to tell me what I can improve.
JSFiddle: https://jsfiddle.net/5837nmyo/
JSBin: https://jsbin.com/yadixolica/1/edit?html,js,output
let sData = {}
sData.label = ["08-Aug-2019","11-Aug-2019","22-Aug-2019","25-Aug-2019"]
sData.time = ["1:08","1:44","2:27","1:02"]
let chartData = {}
chartData.label = sData.label
chartData.time = parseTimeToSeconds(sData.time)
function parseTimeToSeconds(times){
let regex = /(\d*):(\d{2})/gm
let parsedTime = []
for (let x = 0; x < times.length; x++) {
let match = regex.exec(times)
parsedTime.push(parseInt(match[1])*60 + parseInt(match[2]))
}
return parsedTime
}
let time_ctx = document.getElementById('time_chart');
let time_data = {
labels: chartData.label,
datasets: [{
label: chartData.label,
data: chartData.time
}]
};
let time_options = {
responsive: true,
title: {
display: false
},
legend: {
display: false
},
tooltips: {
callbacks: {
label: function(tooltipItem, data){
let value = parseInt(tooltipItem.value)
if (value%60 < 10)
return Math.floor(value/60) + ":" + 0 + value%60
else
return Math.floor(value/60) + ":" + value%60
}
}
},
scales: {
xAxes: [{
type: 'time'
}],
yAxes: [{
ticks: {
min: 0,
max: 1800,
stepSize: 120,
callback: function(value, index, values) {
if (value%60 < 10)
return Math.floor(value/60) + ":" + 0 + value%60
else
return Math.floor(value/60) + ":" + value%60
}
}
}]
}
};
let chart2 = new Chart(time_ctx, {
type: "line",
data: time_data,
options: time_options
});

not able to get the x axis and y -axis data or values from php array using canvaschart js using php

first page screen shots
second page screen shots
not able to display the x- axis and y-axis data from array in canvaschart js using php or zendframework and mysql
<?php
namespace Dashboard\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Session\Container;
use Application\Entity\PyPayGroup;
use Application\Entity\PyPayPeriod;
use Zend\Session\SessionManager;
use Application\Entity\CommonCompanyHeader;
use Dashboard\Form\PayrollspendForm;
class PayrollspendController extends AbstractActionController
{
private $entityManager;
private $payrollspendManager;
private $sessionContainer;
private $pyPayPeriodClass;
private $pyPayGroupClass;
private $companyClass;
public function __construct($entityManager,$payrollspendManager)
{
$this->payrollspendManager = $payrollspendManager;
$this->entityManager = $entityManager;
$this->pyPayGroupClass = $this->entityManager->getRepository(PyPayGroup::class);
$this->pyPayPeriodClass = $this->entityManager->getRepository(PyPayPeriod::class);
$this->companyClass = $this->entityManager->getRepository(CommonCompanyHeader::class);
$sessionManager = new SessionManager();
$this->sessionContainer = new Container('ContainerNamespace', $sessionManager);
$arrLabel = ['payroll_calendar','label_payroll_group','emp_id','emp_name','label_total_earnings','label_payroll_period','company','label_process_id','session_id','label_employer_contribution','pay_item'];
}
public function addAction()
{
if ($this->sessionContainer->empId == "") {
return $this->redirect()->toRoute('admin_user_login');
}
if (!in_array('PY', $this->sessionContainer->arrRole)) {
if (!in_array('py_admin', $this->sessionContainer->arrRole)) {
return $this->redirect()->toRoute('dashboard_ess_index');
}
}
$reportForm = new PayrollspendForm();
$payGroup = $this->pyPayGroupClass->findBy([
'ouCode' => $this->sessionContainer->ouCode,
'langCode' => $this->sessionContainer->langCode,
'pgActive' => 1
]);
$reportForm->buildPayGroupData($payGroup);
$company = $this->companyClass->findBy([
'ouCode' => $this->sessionContainer->ouCode,
'langCode' => $this->sessionContainer->langCode
]);
$reportForm->buildCompanyData($company);
$payPeriodData = ['' => 'Select'];
$reportForm->get('payPeriod')->setValueOptions($payPeriodData);
$postData = $this->getRequest()->getPost()->toArray();
$postData['ouCode'] = $this->sessionContainer->ouCode;
$postData['langCode'] = $this->sessionContainer->langCode;
$compData = $this->payrollspendManager->buildCTCCompensationData($postData);
$groupByData = [
'' => 'Select',
'location' => 'Location',
'department' => 'Department',
'cost-center' => 'Cost center'
];
$reportForm->get('groupby')->setValueOptions($groupByData);
return new ViewModel([
'form' => $reportForm,
'ouCode' => $this->sessionContainer->ouCode,
'reportData' => $compData ,
'langCode' => $this->sessionContainer->langCode,
]);
}
This is model
public function getAllCTCCompensationData($postData)
{
$queryBuilder = $this->entityManager->createQueryBuilder();
$queryBuilder->select('ppp.payperiodSdesc , ppesa.grossPay, pptpp.pfEmployerContribution, pptpp.esiEmployerContribution, pplw.employercontribution')
->from(PyProcessEmpStatusApproved::class, 'ppesa')
->leftJoin(PyProcessTdsPfPt::class, 'pptpp', 'with', 'ppesa.ouCode = pptpp.ouCode')
->leftJoin(PyPayGroup::class, 'ppg', 'with', 'pptpp.pgCode = ppg.pgCode')
->leftJoin(PyProcessLabourWelfare::class, 'pplw', 'with', 'ppg.pgCode = pplw.pgCode')
->leftJoin(PyPayPeriod::class,'ppp','with','pplw.payperiodCode = ppp.payperiodCode')
->leftJoin(PyPayrollCalendar::class, 'ppc', 'with', 'ppp.paycalCode = ppc.paycalCode')
->where('ppesa.ouCode = ?1')
->andWhere('ppesa.langCode = ?2')
->setParameter('1', $postData['ouCode'])
->setParameter('2', $postData['langCode'])
->setMaxResults(60);
$compData = $queryBuilder->getQuery()->getResult();
$data = [];
if(!empty($compData))
{
$total = 0;
foreach($compData as $dataC)
{
$statData = $this->getStatuoryData($postData,$dataC['payperiodSdesc']);
if(isset($statData['payperiodSdesc']))
{
$data[$dataC['payperiodSdesc']]['PAYPERIOD'] = $this->payPERIODdata($postData,$dataC['payperiodSdesc']);
}
else
{
$data[$dataC['payperiodSdesc']]['PAYPERIOD'] = $this->payPERIODdata($postData,$dataC['payperiodSdesc']);
}
if(isset($statData['pfEmployerContribution']))
{
$data[$dataC['payperiodSdesc']]['PF'] = $this->getPFData($postData,$dataC['payperiodSdesc']);
}
else
{
$data[$dataC['payperiodSdesc']]['PF'] = $this->getPFData($postData,$dataC['payperiodSdesc']);
}
if(isset($statData['pfPensionFund']))
{
$data[$dataC['payperiodSdesc']]['PFF'] = $this->getPFData($postData,$dataC['payperiodSdesc']);
}
else
{
$data[$dataC['payperiodSdesc']]['PFF'] = $this->getPFData($postData,$dataC['payperiodSdesc']);
}
if(isset($statData['grossPay']))
{
$data[$dataC['payperiodSdesc']]['GROSS'] = $this->getGROSSPAYData($postData,$dataC['payperiodSdesc']);
}
else
{
$data[$dataC['payperiodSdesc']]['GROSS'] = $this->getGROSSPAYData($postData,$dataC['payperiodSdesc']);
}
if(isset($statData['employercontribution']))
{
$data[$dataC['payperiodSdesc']]['LABOURWELFARE'] = $this->getEMPLOYERCONTRIBUTIONData($postData,$dataC['payperiodSdesc']);
}
else
{
$data[$dataC['payperiodSdesc']]['LABOURWELFARE'] = $this->getEMPLOYERCONTRIBUTIONData($postData,$dataC['payperiodSdesc']);
}
if(isset($statData['esiEmployerContribution']))
{
$data[$dataC['payperiodSdesc']]['ESIC'] = $this->getESICData($postData,$dataC['payperiodSdesc']);
}
else
{
$data[$dataC['payperiodSdesc']]['ESIC'] = $this->getESICData($postData,$dataC['payperiodSdesc']);
}
$data[$dataC['payperiodSdesc']]['Total'] = $this->getCTCCompensationSum($postData,
isset($data[$dataC['payperiodSdesc']]['payperiodSdesc']),
isset($data[$dataC['payperiodSdesc']]['pfEmployerContribution']),
isset($data[$dataC['payperiodSdesc']]['pfPensionFund']),
isset($data[$dataC['payperiodSdesc']]['esiEmployerContribution']),
isset($data[$dataC['payperiodSdesc']]['grossPay']),
isset($data[$dataC['payperiodSdesc']]['employercontribution']));
$data = [$data[$dataC['payperiodSdesc']]['Total']];
}
}
return $data;
}
This is view file or canvaschartjs
<script>
window.onload = function () {
var chart1 = new CanvasJS.Chart("chartContainer1", {
animationEnabled: true,
title: {
text: ""
},
axisX: {
labelFontColor: "#000000",
labelFontStyle: "oblique",
},
axisY: {
title: "",
titleFontColor: "#4F81BC",
lineColor: "#4F81BC",
labelFontColor: "#4F81BC",
tickColor: "#4F81BC"
},
axisY2: {
title: "",
titleFontColor: "#C0504E",
lineColor: "#C0504E",
labelFontColor: "#C0504E",
tickColor: "#C0504E"
},
toolTip: {
shared: true
},
legend: {
cursor: "pointer",
itemclick: toggleDataSeries
},
data: [{
type: "column",
name: "Total",
legendText: "Total",
showInLegend: true,
dataPoints: [
<?php
echo '<pre>';
print_r($compData);
die;
if(!empty($compData))
{
?>
<?php
foreach($compData as $key => $value)
{
?>
{label: "<?php echo $key; ?>", y:<?php echo $value[$data[$dataC['payperiodSdesc']]['Total']]; ?>},
<?php } ?>
<?php } ?>
]
},
{
type: "column",
name: "Closed",
legendText: "Closed",
showInLegend: true,
dataPoints: [
<?php
if(!empty($compData))
{
?>
<?php
foreach($compData as $key => $value)
{
?>
{label: "<?php echo $key; ?>", y: <?php echo $value[$data[$dataC['payperiodSdesc']]['Total']]; ?>},
<?php } ?>
<?php } ?>
]
},
{
type: "column",
name: "Lapsed",
legendText: "Lapsed",
showInLegend: true,
dataPoints: [
<?php if(!empty($compData)) { ?>
<?php foreach($compData as $key => $value) { ?>
{label: "<?php echo $key; ?>", y: <?php echo $value[$data[$dataC['payperiodSdesc']]['Total']]; ?>},
<?php } ?>
<?php } ?>
]
}]
});
}
chart1.render();
}
</script>
<script>
window.onload = function () {
var chart1 = new CanvasJS.Chart("chartContainer1", {
animationEnabled: true,
title: {
text: ""
},
axisX: {
labelFontColor: "#000000",
labelFontStyle: "oblique",
},
axisY: {
title: "",
titleFontColor: "#4F81BC",
lineColor: "#4F81BC",
labelFontColor: "#4F81BC",
tickColor: "#4F81BC"
},
axisY2: {
title: "",
titleFontColor: "#C0504E",
lineColor: "#C0504E",
labelFontColor: "#C0504E",
tickColor: "#C0504E"
},
toolTip: {
shared: true
},
legend: {
cursor: "pointer",
itemclick: toggleDataSeries
},
data: [{
type: "column",
name: "Total",
legendText: "Total",
showInLegend: true,
dataPoints: [
<?php
echo '<pre>';
print_r($compData);
die;
if(!empty($compData))
{
?>
<?php
foreach($compData[0] as $key => $value)
{
?>
{label: "<?php echo $key; ?>", y:<?php echo $value[$data[$dataC['payperiodSdesc']]['Total']]; ?>},
<?php } ?>
<?php } ?>
]
},
{
type: "column",
name: "Closed",
legendText: "Closed",
showInLegend: true,
dataPoints: [
<?php
if(!empty($compData))
{
?>
<?php
foreach($compData[1] as $key => $value)
{
?>
{label: "<?php echo $key; ?>", y: <?php echo $value[$data[$dataC['payperiodSdesc']]['Total']]; ?>},
<?php } ?>
<?php } ?>
]
},
{
type: "column",
name: "Lapsed",
legendText: "Lapsed",
showInLegend: true,
dataPoints: [
<?php if(!empty($compData)) { ?>
<?php foreach($compData[2] as $key => $value) { ?>
{label: "<?php echo $key; ?>", y: <?php echo $value[$data[$dataC['payperiodSdesc']]['Total']]; ?>},
<?php } ?>
<?php } ?>
]
}]
});
function toggleDataSeries(e) {
if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
} else {
e.dataSeries.visible = true;
}
}
chart1.render();
}
</script>
I am trying to draw a barchart of months of x-axis and Total spend on y-axis in graph.In controller class the data which i m sending to the view is $compData = $this->payrollspendManager->buildCTCCompensationData($postData);
The x-axis will show the month ie $data[$dataC['payperiodSdesc']]['PAYPERIOD'] and y-axis will show the total spend ie $data[$dataC['payperiodSdesc']]['Total']. This month and total spend you will find in model.
Here i m using canvasjs using zendframework.Now my data ie $compData is send from controller to view file.This compData has 7 elements and i want to display the zero elemnet in y-axis and sixth element in x-axis.
for canvasjs refer to https://canvasjs.com website using php.
if anybody require more code ...will help you
what is the issue in the code?
The graph should have both x-axis and y-axis.
i m recieving the data in controller in the form of array($compData).
This array i m sending it to view.
Then the array goes in foreach loop and display the zero element from array on x axis and last field ie 6th element on y-axis.
i m displaying the data on x and y-axis dynamically using canvas
js chart.
how to display the graph using canvaschart js ?
if anybody not getting clear about question can ask more for clearty
i m trying to draw a barchart of months of x-axis and Total spend on y-axis in graph
.In controller class the data which i m sending to the view is $compData = $this->payrollspendManager->buildCTCCompensationData($postData);
THe x-axis will show the month ie $data[$dataC['payperiodSdesc']]['PAYPERIOD'] and y-axis will show the total spend ie $data[$dataC['payperiodSdesc']]['Total'] .This month and total spend you will find in model.
here i m using canvasjs using zendframework.Now my data ie $compData is send from controller to view file.This compData has 7 elements and i want to display the zero elemnet in y-axis and sixth element in x-axis.
for canvasjs refer to https://canvasjs.com website using php.
i want to display the PAYPERIOD which is the first array from details array and Total from Details which is last array

Use Jquery to getJSON data feed, and display multiple json array objects in HTML

I am using jquery and getJSON to GET a data feed constructed by PHP. The Feed displays fine when visiting the PHP page. The problem I am running into is that the JSON feed returns as multiple objects when it is GET requested in jQuery, and I don't know how to write the jQuery to display all objects and their data.
jQuery:
$(document).ready(function () {
$("#display_results").hide();
$("#searchButton").click(function (event) {
$("#display_results").show();
event.preventDefault();
search_ajax_way();
});
$("#search_results").slideUp();
$("#searchBox").keyup(function (event) {
$("#display_results").show();
});
});
function search_ajax_way() {
//var search_this=$("#searchBox").val();
//$.post("http:/url.com/folder/cl/feed.php", {city : search_this}, function(data){
//$("#display_results").html(data);
//});
var search_this = $("#searchBox").val();
$.getJSON('http://url.com/app/cl/disp_byowner_feed.php', {
city: search_this
}, function (result) {
$.each(result, function (i, r) {
console.log(r.seller);
window.title = r.title;
window.seller = r.seller;
window.loc = r.location;
(Plan on listing all keys listed in the data feed below here)
});
console.log(result);
$("#display_results").html(window.seller + < need to list all keys / values here > );
});
}
PHP (Constructs JSON Feed):
$city = 'Kanosh';
$s = "SELECT * FROM `list` WHERE `city` LIKE '%".$city."%'";
$res = $mysqli->query($s) or trigger_error($mysqli->error."[$s]");
$a = array();
while($row = $res->fetch_array(MYSQLI_BOTH)) {
$a[] = array(
'title' => $row['title'],
'price' => $row['price'],
'rooms' => $row['rooms'],
'dimensions' => $row['dimensions'],
'location' => preg_replace('pic\u00a0map', '', $row['location']),
'price' => $row['price'],
'address' => $row['address'],
'seller' => $row['seller'],
'href' => $row['href'],
'date' => $row['date']
);
}
header('Content-Type: application/json');
echo json_encode($a);
$res->free();
$mysqli->close();
Sample JSON Feed:
[{
"title": "Great Ski-In Location with Seller Financing Available ",
"price": " (Park City near the Resort) ",
"rooms": "",
"dimensions": "",
"location": "",
"address": "Crescent Road at Three Kings Dri",
"seller": "real estate - by owner",
"href": "http:\/\/saltlakecity.craigslist.org",
"date": "20140811223115"
}, {
"title": "Prospector Building 1 - Tiny Condo, Great Location - Owner Financing",
"price": "$75000",
"rooms": false,
"dimensions": "",
"location": " Prospector Square Park City Ut",
"address": "",
"seller": "real estate - by owner",
"href": "http:\/\/saltlakecity.craigslist.org",
"date": "20140811223115"
}]
Your output is an Array of JSON objects.
Fortunately, JavaScript is convenient for manipulating JSON (actually, that is why JSON was created..), and jQuery is convenient for manipulating the DOM.
To parse the result, you can just iterate through that Array, construct whatever HTML string that you need within the Array, and then insert it into the DOM using jQuery.
Here a simple example with lists :
var html = "";
for (var i = 0; i < result.length; i++) { //assuming result in the JSON array
html += '<ul id = 'house_' + i>';
for (var property in result[i]) { //read all the object properties
html += '<li>' + property + ' : ' + result[i][property] + '</li>';
}
html += '</ul>';
};
$("whatever_div").html(html);
If you only want to display some of the properties, you can read them separately and do additional formatting (for the date for example).
It is also useful to give the different HTML objects ids corresponding to what they represent.
function search_ajax_way(){
//var search_this=$("#searchBox").val();
//$.post("http:/url.com/folder/cl/feed.php", {city : search_this}, function(data){
//$("#display_results").html(data);
//});
var search_this=$("#searchBox").val();
$.getJSON('http://hooley.me/scraper/cl/disp_byowner_feed.php', { city : search_this }, function(result) {
var output = '';
$.each(result, function(i,r) {
output+= r.title + " " + r.seller
});
$("#display_results").html(output);
});
}

Flot Charts using SQL Server db with multiple y axis

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);

javascript php mysql flot database

everyone! I have issues with regard to my x-axis. I'm using the api of flot. In my case, I'm extracting data from mysql to plot the graph. Both axes requires data to be extracted from mysql. For example, mysql will extract a data for the Y axis, say 20. My x axis will extract data from mysql of that particular time.
I tried to rewrite the script a few times, but to no conclusion. I tried attempting to create a variable, options, but it didn't work. It works only if I place the x axis statement just below y. The whole idea of creating a new variable options because I wanted to do a loop for the x-axis to continouous collect data from mysql. In the below quote, I simulated it with selected arrays.
$(function () {
var graph = [];
var power = <?php echo json_encode($data);?>;
var time = <?php echo json_encode($times);?>;
var row = <?php echo json_encode($nrow);?>;
//alert(time.toSource());
for (var i = 1; i < row; i += 1) {
//var test = time[i];
//alert(test);
//graph.push([i, power[i]]);
var hhmm = time[i].split(":");
var hh = parseInt(hhmm[0]);
var mm = parseInt(hhmm[1])/60;
var tt = hh+mm;
//var tx = hh;
graph.push([tt, power[i]]);
}
var options = {
xaxis: { ticks:[[1,time[1]],[2,time[2]],[3,time[3]],[4,time[4]],[5,time[5]],[6,time[6]],[7,time[7]],[8,time[8]]]}
};
//alert(options.toSource());
var plot = $.plot($("#placeholder"),
[ { data: graph, label: "Power" } ], {
series: {
lines: { show: true },
points: { show: true }
},
grid: { hoverable: true, clickable: true },
yaxis: { min: 0, max: 25 },
//xaxes: [ { mode: 'time' } ]
//xaxis: { mode: "time"}
//xaxis: { mode: "time",timeformat:"%H/%M" }
//xaxis: { ticks:[[1,time[1]],[2,time[2]],[3,time[3]],[4,time[4]],[5,time[5]],[6,time[6]],[7,time[7]]]}
}), options);
I have changed the options function, but it doesn't work.
var options = {
series: {
lines: { show: true },
points: { show: true }
},
grid: { hoverable: true, clickable: true },
yaxis: { min: 0, max: 25 },
for (var i = 1; i < row; i += 1)
{
xaxis: { ticks:[[i,time[i]]}
};
};
If I've surmised the format you wish for xaxis correctly, you could try the following:
var ticks = [];
for (var i = 1; i < row; i += 1)
{
ticks.push ([i, time[i]]);
}
var xaxis = {
ticks: ticks,
// ... any additional properties...
};
This will create an object xaxis with the property ticks which in turn is an array of arrays where each sub-array has two elements, the counter starting with one and the value of the time array for each i. I suppose you'll want to use code similar to this to create options:
var options = {
series: { lines: { show: true },
points: { show: true } },
grid: { hoverable: true, clickable: true },
yaxis: { min: 0, max: 25 },
xaxis: xaxis
};
You cannot use the for() statement in the object initialization, you'll have to create the xaxis array before, and use the variable name when creating the options object.

Categories