I'm trying to create a range area chart using CanvasJS and PHP to load the data from a database.
I've created the php and it returns the values from the DB.
Here is the php:
<?php
header('Content-Type: application/json');
$con = mysqli_connect("127.0.0.1","root","pwd1","db");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}else
{
$data_points = array();
$result = mysqli_query($con, "select (CalYear+1) as CalYear, concat('[',REPLACE(Year1PercWC,',','.'),',',REPLACE(Year1PercBC,',','.'),']') as ResultSet, concat('Sessies: ',calyear) as Help FROM table where cat='1' and (CalYear+1)<year(now())");
while($row = mysqli_fetch_array($result))
{
$point = array("x" => $row['CalYear'] , "y" => $row['ResultSet'],"name" => $row['Help']);
array_push($data_points, $point);
}
echo json_encode($data_points);
}
mysqli_close($con);
?>
With the results:
[{"x":"2007","y":"[35.94,35.94]","name":"Sessies: 2006"},{"x":"2008","y":"[27.67,27.67]","name":"Sessies: 2007"},...,...]
The problem are the quotes in the x and y values (=string values). CanvasJS only takes numbers to create a graph. So the output should be like:
[{"x":2007,"y":[35.94,35.94],"name":"Sessies 2006"},{"x":2008,"y":[27.67,27.67],"name":"Sessies 2007"},...,...]
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="jquery.canvasjs.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("TestGraf.php", function (result) {
var chart = new CanvasJS.Chart("chartContainer", {
axisX: {
intervalType: "number",
title: "Year",
interval: 1,
valueFormatString: "#"
},
data: [
{
type: "rangeArea",
dataPoints: result
[{"x":2007,"y":[35.94,35.94],"name":"Sessies 2006"},{"x":2008,"y":[27.67,27.67],"name":"Sessies 2007"}] -- This is working fine
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 380px;"></div>
</body>
</html>
I'm sure there must be a way to adapt my php so that x and y are passed through as numbers instead of strings, but i'm really new at php (first time ever) and can't find the solution,especially for the second part (y).
Can anyone tell me which adaptions to make to the php and/or html file?
Thx,
This should probably work for you :
json_encode($arr, JSON_NUMERIC_CHECK);
It's probably a little too late for my answer but like Alex answered, you should use echo json_encode($data_points, JSON_NUMERIC_CHECK);
The numeric check is an option. See http://php.net/manual/en/json.constants.php
However, more understanding of how a range area chart works seems to be the problem. The range area chart has an X and 2 Y values. The 2 Y values are needed to plot the range. If you simply go to the testgraf.php file in your browser, your JSON result should be:
[{x: somevalue, y:[low_value, high_value]}]
You might have to change your sql statement to get another y value. You can do what you want with that. Anyway, this is what you should do for your php code:
Change
$point = array("x" => $row['CalYear'] , "y" => $row['ResultSet'],"name" => $row['Help']);
to:
$point = array("x" => $row['CalYear'] , "y" => $row['ResultSet', 'some_value'],"name" => $row['Help']);
If your 2 Y values don't change, you may not see a graph line diplayed. Would a line graph be more appropriate?
After some trial and error I found the following solution:
$result1 = mysqli_query($con, "select (CalYear+1) as CalYear, Year1PercWC, Year1PercBC, calyear as Help FROM table_2 where cat='1' and (CalYear+1)<year(now())");
while($row = mysqli_fetch_array($result1))
{
$point = array("x" => floatval($row['CalYear']),"y" => array(floatval($row['Year1PercWC']),floatval($row['Year1PercBC'])),"name" => floatval($row['Help']));
array_push($data_points, $point);
}
echo json_encode($data_points);
The problem was I needed to create an array for my Y-values in the array for the datapoints. In this array I could store the 2 values I needed for the graph.
After this was done I needed to transform al the numeric values to float_val so that the quotes around the values disappeared.
Thx for the help everyone :)
Related
I'm a 'newbie' on stackoverflow but it is a source that I keep coming to regularly for tips.
I've picked up some code from the simple.html file accompanying the jsPDF auto-table plug-in but as it doesn't appear to pick up data from a php generated table.
I am trying to get the data into a format that can be transformed into a nice pdf report - 'with all the trimmings' - ie; page-breaks, headers on each page, alternate row-colours etc.
I've tried to get the data into a form that can be used by the jsPDF autotable but I'm going wrong in that it is just going through the array and keeping the last record and printing that in pdf format. Code shown below.
<button onclick="generate()">Generate pdf</button>
<script src="/js//jspdf.debug.js"></script>
<script src="/js/jspdf.plugin.autotable.js"></script>
<?php
$link = mysqli_connect('localhost','user','password','database');
if(!$link)
{
echo 'Database Error: ' . mysqli_connect_error() ;
exit;
}
$results=array();
$sql_staff = "SELECT staff_id, staff_firstname, staff_lastname, staff_username, staff_chargerate, staff_lastlogin FROM tblstaff ORDER BY staff_lastname ASC, staff_firstname ASC ";
$result_staff = mysqli_query($link,$sql_staff);
while($row = mysqli_fetch_array($result_staff)){
$results[0] = $row['staff_id'];
$results[1] = $row['staff_firstname'] . " " . $row['staff_lastname'];
$results[2] = $row['staff_username'];
$results[3] = $row['staff_chargerate'];
$results[4] = $row['staff_lastlogin'];
echo json_encode($results);
$data = json_encode($results);
}
?>
<script>
function generate() {
var head = [["ID", "Staff Name", "Username", "Charge-rate", "Last Log-in"]];
var body = [
<?echo $data;?>
];
var doc = new jsPDF();
doc.autoTable({head: head, body: body});
doc.output("dataurlnewwindow");
}
</script>
I think that the problem lays around the line $data = json_encode($results); but I don't know enough about either PHP or Javascript to determine how the code needs to be altered to produce a full PDF report. Can anyone assist please?
Your issue is probably related to overwriting the values in the $results array which means you will get one item instead of an array of items. You probably want something like this:
$results = array();
while($row = mysqli_fetch_array($result_staff)){
$dataRow = array();
array_push($dataRow, $row['staff_id']);
array_push($dataRow, $row['staff_firstname'] . " " . $row['staff_lastname']);
// etc
array_push($results, $dataRow);
}
$data = json_encode($results);
So many question regarding javascript and so sorry about it. I have create yet a small chart which i promised one of the member/mentor here that I will study real hard in javascript.
So here I am creating a small yet perfect chart but the word perfect seems not fit for it for it returns a wrong display.
Here's the code for the php/html file with the ajax $.getJSON
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script src="canvasjs.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("data.php", function (result) {
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: result
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 380px;"></div>
</body>
</html>
Now here's the data to be pulled from database
So there are actually 5 types of dogs based on animal_id
LARGE,MEDIUM,SMALL,PUPPY,DISABLED
Now Here's the data.php
<?php
header('Content-Type: application/json');
$con = mysqli_connect("localhost","root","","siglo");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}else
{
$data_points = array();
$result = mysqli_query($con, "SELECT animal_id,FROM_UNIXTIME(microtime,' %M ') as microtimes, SUM(srp) as admitting_cost FROM vet_table WHERE microtime BETWEEN UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 180 day)) and 1480723199 GROUP BY telco_id, microtimes");
while($row = mysqli_fetch_array($result))
{
$point = array("label" => $row['microtimes'] , "y" => $row['admitting_cost'],);
array_push($data_points, $point);
}
echo json_encode($data_points, JSON_NUMERIC_CHECK);
}
mysqli_close($con);
?>
This is the result
I can't simply find where I went wrong and the result must be at the bottom is the months and then each month should have 5 bar corresponding to admitting cost
So let's say animal_id 091092010290192(sample) has accumulated 600 on august, 500 on september and on.....like that
Please help.
The code I am using is below.
I want to make a simple graph based on the data from my database table.
It is working now but I want date on the bottom axis is not appearing properly.
while the value of variable is
[25-03-15, 1236], [26-03-15, 3000], [27-03-15, 3054], [30-03-15, 4000]
that is right. But I cant get this date on the x-axis. any solution there?
The way I am getting getting this value is
<?php
$usd=$this->db->query('select transaction_date, SUM(amount) as total from transactions GROUP BY transaction_date')->result_array();
$str = '';
for($i=0; $i<count($usd); $i++){
if($i!=0){
$str = $str.', ['.date('d-m-y', strtotime($usd[$i]["transaction_date"])).', '.$usd[$i]["total"].']';
}else{
$str = $str.'['.date('d-m-y', strtotime($usd[$i]["transaction_date"])).', '.$usd[$i]["total"].']';
}
}
echo $str;
?>
Then I pass this data in java script like this:
var graphData = [{
data: [ <?php echo $str; ?>]
}
];
But At the end I can not get the date on x axis.
PS:
I am working on the view of codeigniter application.
Have a look at the documentation for time series data.
You need javascript timestamps. In PHP you get them simply with
strtotime($usd[$i]["transaction_date"]) * 1000
Then your data should look like this:
[1427238000000, 1236], [1427324400000, 3000], ...
For the labels on the x axis, use the timeformat options to get back the format you want:
xaxis: {
mode: "time",
timeformat: "%d-%m-%y"
}
I’m reading X,Y Coordinates from MySQL Database.
2 files, pretend the connection is there : coordinate_array, and map.php
Update here In coordinate_array: I am making a multidimensional arrays so I can then use json_encode($desk). I only need x,y values for the Javascript part.
<?php
include 'db_conn.php';
header('Content-Type: application/json');
$select_coordinate_query = "SELECT x_coord, y_coord FROM coordinates";
$result = mysqli_query($conn,$select_coordinate_query);
//see if query is good
if($result === false) {
die(mysqli_error());
}
//array that will have number of desks in map area
$desk = array(); // just added
while($row = mysqli_fetch_assoc($result)){
//get desk array count
$desk[] = array( array("x" => $row['x_coord']),
array("y" => $row['y_coord'])
);
} //end while loop
echo json_encode($desk); //encode array
?>
The code above gives me this :
[[{"x":"20"},{"y":"20"}],[{"x":"30"},{"y":"30"}],[{"x":"40"},{"y":"40"}],[{"x":"50"},{"y":"50"}]]
In map.php : I am trying to get those value with the use of JQuery. I want to get the values and run a loop that will execute my Paint function which will keep drawing rectangles for every row thats in the table. I am very new with JSON and JQuery and starting to use it.
<canvas id="imageView" width="600" height="500"></canvas>
<script type="text/javascript">
NEED HELP HERE PLEASE
//I have no idea how to get the encoded values
$(document).ready(function(){
$.getJSON('coordinate_array.php', function(data)){
$.each(data, function(k,v){
Paint(v[0].x, v[1].y);
});//end each
});//end get json
});//end rdy func
I WANT TO EXECUTE THIS FUNCTION
//function to paint rectangles
function Paint(x,y)
{
var ctx, cv;
cv = document.getElementById('imageView');
ctx = cv.getContext('2d');
ctx.lineWidth = 5;
ctx.strokeStyle = '#000000';
//x-axis,y-axis,x-width,y-width
ctx.strokeRect(x, y, x+100 , y+100);
}
</script>
Thank you in advance it’s much appreciated!
You're doing the json wrong. it should be encoded AFTER your DB fetch loop completes. Since you're doing the encoding inside the loop, you're spitting out multiple independent JSON-encoded strings, which will be treated as a syntax error on the receiving end.
e.g.
while($something) {
echo json_encode($some_array);
}
will spit out
[something][something][something]
three separate json-encoded arrays jammed up against each other. What you want is something more like this:
while($something) {
build_array();
}
echo json_encode($array);
which would spit out
[something,something,soemthing]
instead.
Try to use
header('Content-Type: application/json');
in coordinate_array.php
I would like to replicate this highcharts column graph: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/column-drilldown/
I'm pulling my data from a table and it looks like this.
I want the Job_Num on the x-axis where brands are in the fiddle, PercentofBudgetedHrs would be the brandsData. Now when you click a job number, it drills down to departments and shows their percentage of budgeted hrs.
I have the first part working, but I'm using different code like so: http://jsfiddle.net/98Fuq/4/
Here is what I changed in that code:
$sql = "SELECT * FROM view_percentof_budgeted WHERE PercentofBudgetedHrs < 1000 && PercentofBudgetedHrs IS NOT NULL";
$result = mysqli_query($dbc3, $sql);
while($row = mysqli_fetch_assoc($result)) {
$jobNum[] = $row['Job_Num'];
$jobData[$row['Job_Num']] = $row['PercentofBudgetedHrs'];
$jobDrillData[$row['Job_Num']][] = $row;
}
The part I changed in the JS:
var colors = Highcharts.getOptions().colors,
categories = [<?php echo join($jobNum, ',') ?>],
name = '% of budgeted hours',
level = 0,
data = [
<?php echo join($jobData, ',') ?>,
];
function setChart(name, categories, data, color, level) {
chart.xAxis[0].setCategories(categories);
chart.series[0].remove();
chart.addSeries({
name: name,
data: data,
level: level,
color: color || 'red'
});
}
How do I go about doing it the way that first fiddle I posted does it? I like my method of pulling the data from a table so I don't want to use a tsv, I'm just confused on the drilldown part. I've looked at examples but can't seem to figure it out.
Instaed of using join() I advice to prepare correct strucutre of arrays in php, then use json_encode() including JSON_NUMERIC_CHECK flag. As a result you can get this json by $.getJSON and put in highcharts.