Hello there I need to represent data in graph form(chart form). For this I am using a jQuery plugin .The problem I am having is when I do this using PHP array its not working for me.
The code I am using is here.
<html>
<head>
<title>JSChart</title>
<script type="text/javascript" src="../../../sources/jscharts.js"></script>
</head>
<body>
<div id="graph">Loading graph...</div>
<?php
$phpArray = array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
$aa= json_encode($phpArray);
?>
<script type="text/javascript">
var myData = <?php echo $aa; ?>;
alert(myData);
var colors = ['#AF0202', '#EC7A00', '#FCD200', '#81C714'];
var myChart = new JSChart('graph', 'bar');
myChart.setDataArray(myData);
myChart.colorizeBars(colors);
myChart.setTitle('Year-to-year growth in home broadband penetration in U.S.');
myChart.setTitleColor('#8E8E8E');
myChart.setAxisNameX('');
myChart.setAxisNameY('%');
myChart.setAxisColor('#C4C4C4');
myChart.setAxisNameFontSize(16);
myChart.setAxisNameColor('#999');
myChart.setAxisValuesColor('#7E7E7E');
myChart.setBarValuesColor('#7E7E7E');
myChart.setAxisPaddingTop(60);
myChart.setAxisPaddingRight(140);
myChart.setAxisPaddingLeft(150);
myChart.setAxisPaddingBottom(40);
myChart.setTextPaddingLeft(105);
myChart.setTitleFontSize(11);
myChart.setBarBorderWidth(1);
myChart.setBarBorderColor('#C4C4C4');
myChart.setBarSpacingRatio(50);
myChart.setGrid(false);
myChart.setSize(616, 321);
myChart.setBackgroundImage('chart_bg.jpg');
myChart.draw();
</script>
</body>
</html>
And the below code is running perfectly.(with javascript array)
<script type="text/javascript">
var myData = new Array(['Mar04-Mar05', 21], ['Mar05-Mar06', 28], ['Mar06-Mar07', 12], ['Mar07-Mar08', 17]);
alert(myData);
var colors = ['#AF0202', '#EC7A00', '#FCD200', '#81C714'];
var myChart = new JSChart('graph', 'bar');
myChart.setDataArray(myData);
myChart.colorizeBars(colors);
myChart.setTitle('Year-to-year growth in home broadband penetration in U.S.');
myChart.setTitleColor('#8E8E8E');
myChart.setAxisNameX('');
myChart.setAxisNameY('%');
myChart.setAxisColor('#C4C4C4');
myChart.setAxisNameFontSize(16);
myChart.setAxisNameColor('#999');
myChart.setAxisValuesColor('#7E7E7E');
myChart.setBarValuesColor('#7E7E7E');
myChart.setAxisPaddingTop(60);
myChart.setAxisPaddingRight(140);
myChart.setAxisPaddingLeft(150);
myChart.setAxisPaddingBottom(40);
myChart.setTextPaddingLeft(105);
myChart.setTitleFontSize(11);
myChart.setBarBorderWidth(1);
myChart.setBarBorderColor('#C4C4C4');
myChart.setBarSpacingRatio(50);
myChart.setGrid(false);
myChart.setSize(616, 321);
myChart.setBackgroundImage('chart_bg.jpg');
myChart.draw();
</script>
</body>
</html>
The chart object is expecting a 2D array (an array inside an array).
If you look in the HTML source you will see that json_encode is giving you an object, which would look something like this:
{"Peter", "35", "Ben", "37", "Joe", "43"}
try using this:
function create_2d_array($array) {
if (count($array) == 0)
return "[]";
$results = "[";
foreach ($array as $key => $value) {
$results .= "[\"$key\", $value], ";
}
$results = substr($results, 0, strlen($results) - 2);
return $results . "]";
}
and in the javascript area:
var myData = <?php echo create_2d_array($phpArray) . ';'; ?>;
Related
I am not being able to show the values from my PHP file into my HTML file using Chart js. I am trying to import it through AJAX request. I tried it through printing the database value as JSON in the PHP file. The encoding worked well but I can't show them in graph for some reason. Please suggest any other way if possible to do the task mentioned in the code
HTML:
<html>
<head>
<meta charset="utf-8"/>
<title>Chart.js demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/0.2.0/Chart.min.js" type="text/javascript"></script>
<script src="assets/js/jquery.min.js" type="text/javascript"></script>
<script src="assets/js/LineGraph.js" type="text/javascript" ></script>
</head>
<body>
<h1>Chart.js Sample</h1>
<div id= "graphDiv" style="width:100%; height:auto;">
</div>
<script>
showGraph();
function showGraph(){
$.post("agSensorInterfaceUpdate.php", function (data){
console.log(data);
var ctx = $("#graphCanvas");
var acc_data = [];
var gyr_data = [];
var serial = [];
for(var i in data) {
acc_data.push(data[i].accelerometer);
gyr_data.push(data[i].gyroscope);
serial.push(data[i].serial_no);
}
var chartdata = {
labels: serial_no,
datasets: [
{
label: 'Accelerometer Data',
backgroundColor: 'rgba(200,200,0.75)',
borderColor: 'rgba(200,200,0.75)',
hoverBackgroundColor: 'rgba(200,200,200,1)',
hoverBorderColor: 'rgba(200,200,200,1)',
data: acc_data
}
]
};
var lineGraph = new Chart(ctx, {
type:'line',
data: chartdata
});
});
}
</script>
</body>
PHP:
<?php
header('Content-Type: application/json');
$username = "root";
$password = "";
$database = "arthor_bb";
$serial=1;
$sensor_value = array();
$mysqli = new mysqli("localhost", $username, $password, $database);
$query = "SELECT * FROM `sensor_data`";
$result = $mysqli->query($query);
foreach ($result as $row){
$sensor_value[] = $row;
}
$result -> close();
print json_encode($sensor_value);
?>
your "graphDiv" html element needs to be a canvas. not a div.
<canvas id="myChart" width="100%" height="50%"></canvas>
You also have the wrong id on your ctx variable.
let ctx = document.getElementById('myChart').getContext('2d'); // canvas
I'm making a virtual worlds. I need to add players. Is it possable to make a php function that finds all the data in a database/player data and turns each line into a variable so I can tranfer it into javascript. The function would look something like,
function data() {
Finddata_from("players");
Create var p.$number;
}
You may create the Javascript Code and just echo it.
function data() {
$data = ['john' => 200, 'marc' => 200];
echo '<script>', PHP_EOL;
foreach($data as $playername=> $score) {
printf('var %s = "%s";' . PHP_EOL, $playername, $score);
}
echo '</script>', PHP_EOL;
}
Example output:
<script>
var john = 100;
var marc = 200;
</script>
Writing values to JavaScript on the page is no different than writing values to HTML. Consider the following example of writing a value to HTML:
<div>
<p><?php echo "some value"; ?></p>
</div>
This would result in:
<div>
<p>some value</p>
</div>
From PHP's perspective, there was only that one single PHP statement. Everything else outside of the <?php ?> tags is just text sent directly to the browser without PHP's involvement. What's in that text doesn't matter. It can just as easily be JavaScript. For example:
<script>
var someValue = "<?php echo "some value"; ?>";
alert(someValue);
</script>
Would emit:
<script>
var someValue = "some value";
alert(someValue);
</script>
Try to use a JSON (JavaScript Object Notation):
<?php
$con = mysqli_connect($host, ...);
$sth = mysqli_query($con, "SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
?>
<script>
var _obj = <?php echo json_encode($rows) ?>;
console.log(_obj);
</script>
I need help for a school project. I have been able to pull data from a mySQL database into an array and encoded into JSON, which displays fine. Now, I need help with passing the JSON data to C3 to produce a chart (if possible on the same page).
What I've done so far:
$strQuery = "SELECT production_date,oil FROM production WHERE well = '$h_well' AND production_date BETWEEN '$h_start' AND '$h_end' ORDER BY production_date ASC";
$result = mysqli_query($conn, $strQuery);
// Print out rows
$data = array();
while ( $row = $result->fetch_assoc() ) {
$data[] = $row;
}
echo json_encode( $data );
You need to create two separate array, one for your data and one for dates that you want to show on x-axis and then pass that array to java script.
here is full working example
<?php
$conn = mysqli_connect("localhost", "root", "", "test_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$strQuery = "SELECT production_date,oil FROM production WHERE well = '$h_well' AND production_date BETWEEN '$h_start' AND '$h_end' ORDER BY production_date ASC";
$result = mysqli_query($conn, $strQuery);
// Print out rows
$valuesArray = array();
$datesArray = array();
$valuesArray[] = 'Oil';
$datesArray[] = 'x';
while ($row = $result->fetch_assoc()) {
$datesArray[] = $row['production_date'];
$valuesArray[] = $row['oil'];
}
?>
<html>
<head>
<title>C3 Liner example</title>
<link href="c3_scr/c3.css" rel="stylesheet" type="text/css" />
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="c3_scr/c3.js"></script><!-- load jquery -->
</head>
<body>
<div id="chart"></div>
<script>
var xAxisArr = <?php echo json_encode($datesArray); ?>;
var dataArr = <?php echo json_encode($valuesArray, JSON_NUMERIC_CHECK); ?>;
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'x',
columns: [
xAxisArr,
dataArr
]
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%Y-%m-%d'
}
}
}
});
</script>
</body>
</html>
I'm creating one Graph chart using Google APIs I used Java Script source from Google. In PHP I'm using while loop where I fetch some array row using query, this mysql query works fine, and values of fetched array are also correct (When I echoed that in PHP) but problem is that how do I pass this values to JavaScripts function?
My PHP code is as follows :
while ($graph_result = mysqli_fetch_row($graph))
{
$graphCount = $graph_result[0];
$graphMonth = $graph_result[1];
echo $graphCount; // This works
echo $graphMonth;
}
This gives me in result of two rows, each contains two values listed below:
Now I want to pass this above values to Java script function so that it draws Graph chart for me, my javascript code is as follows:
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Months', 'users'],
[graphMonth, graphCount] // Here I have to place PHP values !
]);
}
So how to pass this values to JS ???
Try the below code,
In PHP
$i = 0;
while ($graph_result = mysqli_fetch_row($graph))
{
$graph_values[$i]["count"] = $graph_result[0];
$graph_values[$i]["month"] = $graph_result[1];
$i++;
}
In script,
<script>
<?php foreach($graph_values as $key){ ?>
drawChart('<?php echo $key["count"]; ?>', '<?php echo $key["month"]; ?>');
<?php } ?>
function drawChart(graphCount, graphMonth) {
var data = google.visualization.arrayToDataTable([
['Months', 'users'],
[graphMonth, graphCount]
]);
}
</script>
<?php while ($graph_result = mysqli_fetch_row($graph))
{
?>
<script>
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Months', 'users'],
[<?php echo $graph_result[0]; ?>, <?php echo $graph_result[1]; ?>]
]);
}
</script>
<?php
}
?>
I don't know if it is best practice or not..
You can use json to do that.
In your while loop, build an associative array and encode it in json:
$jsonArray = array();
while ($graph_result = mysqli_fetch_row($graph))
{
$graphCount = $graph_result[0];
$graphMonth = $graph_result[1];
$jsonArray[] = array($graphCount, $graphMonth);
}
echo '<div id="json">' . json_encode($jsonArray) . '</div>';
And then recover it in your javascript:
var json_data = JSON.parse(document.getElementById('json').innerHTML);
function drawChart(json_data) {
var data = google.visualization.DataTable();
data.addColumn('number','Months');
data.addColumn('number','users');
data.addRows(json_data);
}
This is the weirdest thing i've seen. I have an array that I created with php - then I used JSON_Encode to use it with a FLOT Graph. I echoed out the encoded array once - and it's perfect.
Then randomly, another alert box appears with "null".
Subsequently, the script also has a "null" when i echo it into the javascript.
the var d1 is null when I inspect it...
At first I get an alert box with [[0,50],[1,3],[2,488],[3,25],[4,90],[5,50],[6,90],[7,50],[8,5]] -- then I get a second alert box WHICH I DID NOT CODE with "null".
code:
<?php
$num = 0;
while($row = $sql->fetch(PDO::FETCH_OBJ)){
$line[] = array($num,intval($row->percent));
$num ++;
}
$TEST = json_encode($line);
echo "<script>alert('".$TEST."');</script>";
?>
<script>
var d1 = <?php echo $TEST;?>;
$(document).ready(function () {
$.plot($("#chart"), [d1]);
});
</script>
Output from Inspector:
var d1 = []; //Notice the empty array
$(document).ready(function () {
$.plot($("#chart"), [d1]);
});
Use $line = array(); for empty data from while loop
$line = array();
while(....
You can check empty
if(count($line)!=0) {
$TEST = json_encode($line);
echo "<script>alert('".$TEST."');</script>";
}
UPDATE:
$TEST = json_encode($line);
echo "<script>$.plot($('#chart'), \"<?php echo $TEST; ?>\");</script>";