Line chart is drawn very fine using (int) values using Google Charts API (see exact below code) but one of the percentage column value is in float so I tried (floatval) instead of (int) but PHP server file throws 500 internal server error.
What is the solution in especially at to use float value?
(int)str_replace("%", "", $row['percentage'])
Also note that, my values are coming as JSON from MySQL.
PHP (server file):
$rows[] = array(explode(" - ", $row['started_on'])[0].trim(), 'Coverage');
while($row = mysqli_fetch_array($result)) {
$rows[] = array(explode(" - ", $row['started_on'])[0].trim(), (int)str_replace("%", "", $row['percentage']));
}
JS (in php):
// Draw line chart
function drawLineChart(chartType, chartTitle) {
google.charts.setOnLoadCallback(lineChartData);
function lineChartData() {
var lineChartJsonData = $.ajax({
type: 'GET',
url: "<?php echo $general_scripts; ?>",
data: { id1: chartType, id2: "Chart", id100: "<?php echo $getPage; ?>" },
dataType:"json",
async: false,
beforeSend: function() {
$("#progress").show();
},
success: function(data) {
$("#progress").hide();
},
}).responseText;
var options = {
title: chartTitle,
width: '390',
height: '300',
backgroundColor: '#f5fffa',
};
var data = new google.visualization.arrayToDataTable(($.parseJSON(lineChartJsonData)));
var chart = new google.visualization.LineChart(document.getElementById(chartType));
chart.draw(data, options);
}
}
(float) works fine, here it is:
$rows[] = array(explode(" - ", $row['started_on'])[0].trim(), (float)str_replace("%", "", $row['data']));
echo json_encode($rows);
Give this data to chart.draw(data, options);
Related
PHP: chart_db.php
<?php
require_once ('dbh.inc.php');
$JSON_Response = array();
//Counts the number of Active
$count_active = mysqli_query($db, "SELECT client_id FROM client WHERE status = 1");
$JSON_Response['active'] = mysqli_num_rows($count_active);
//Counts the number of Inactive
$count_inactive = mysqli_query($db, "SELECT client_id FROM client WHERE status = 0");
$JSON_Response['inactive'] = mysqli_num_rows($count_inactive);
error_log('hello');
echo json_encode($JSON_Response);
?>
JS: chart.js
$(document).ready(function(){
$.ajax({
url:"http://localhost/FAME/private/includes/chart_db.php",
method: "GET",
success: function(response){
var data = JSON.parse(response);
var activeData = text(data.active);
var inactiveData = text(data.inactive);
console.log(activeData);
var ctx = document.getElementById('piechart').getContext('2d');
var statusChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['Active', 'Inactive'],
datasets: [{
pointStyle: 'circle',
backgroundColor: [ 'rgb(78, 115, 223)', 'rgb(25, 179, 211)' ],
data: activeData, inactiveData
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
segmentShowStroke: false,
cutoutPercentage: 70,
legend: {
onClick: false,
position: 'bottom',
labels: {
usePointStyle: true
}
}
}
});
}
});
});
Question: The problem is that in the data in chart are not showing. The entire chart is not showing. And with the log from chrome inspection: it says that there is an error: "Uncaught ReferenceError: text is not defined".
This has nothing to do with php, mysql or xampp. You are using an undefined method called text. The error message says it all. Check your third and fourth lines in the ajax success. You have:
var activeData = text(data.active);
Replace it with :
var activeData = data.active;
and see what happens.
I'm using chart.js to generate charts on my page.
However I want these charts to be populated by my SQL database.
I'm able to get my data out of my database, but I won't draw the chart
I got a canvas on my main page called "OmzetChart" , this is where the chart should come.
<script>
$.ajax({
type: 'POST',
url: 'templates/getdata.php',
success: function (data) {
lineChartData = data;
//alert(JSON.stringify(data));
var ctx = document.getElementById("OmzetChart").getContext("2d");
var myLineChart = new Chart(ctx, {
type: 'line',
data: lineChartData
});
}
});
</script>
The page of GetData.php results in the following (This is what I need, just want it into my chart):
[{"dag":"23","0":"23","uur":"13","1":"13","SomOmzet":"23.00","2":"23.00"},{"dag":"23","0":"23","uur":"18","1":"18","SomOmzet":"2.50","2":"2.50"}]
Getdata.php:
<?php
include ("../PDO.php");
$conn = DatabasePDO::getInstance();
$sql = "SELECT DATEPART(DD, receiptdatetime) as dag ,DATEPART(hh, receiptdatetime) as uur, ISNULL(abs(cast(sum(NetAmount) as decimal (10,2))),0) as SomOmzet FROM ReceiptLine a , Receipt b, ReceiptLineDetail c
where a.LineType = 200 and a.receiptID = b.receiptid and a.receiptlineID = c.receiptlineID
group by DATEPART(DD, receiptdatetime), DATEPART(hh, receiptdatetime)";
$st = $conn->prepare($sql);
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$list[] = $row;
}
$conn = null;
echo json_encode( $list );
?>
json_encode() produces a JSON string. You need to parse this with JSON.parse() before you can use it.
$.ajax({
type: 'POST',
url: 'templates/getdata.php',
success: function (data) {
lineChartData = JSON.parse(data); //parse the data into JSON
var ctx = document.getElementById("OmzetChart").getContext("2d");
var myLineChart = new Chart(ctx, {
type: 'line',
data: lineChartData
});
}
});
Also, using $.ajax() method's dataType parameter, you can leave this parsing to jQuery.
$.ajax({
type: 'POST',
url: 'templates/getdata.php',
dataType: 'json', //tell jQuery to parse received data as JSON before passing it onto successCallback
success: function (data) {
var ctx = document.getElementById("OmzetChart").getContext("2d");
var myLineChart = new Chart(ctx, {
type: 'line',
data: data //jQuery will parse this since dataType is set to json
});
}
});
i'm trying to make a modal dialog in html, and when something is pressed to draw a google chart in the modal.
function inter(id)
{
var arr = [['Album','Vizualizari']];
$.ajax({
url: 'popular.php',
type: 'GET',
dataType: 'json',
success: function (json) {
$.each(json,function (i ,value )
{
var c =[value.title, value.popular];
arr.push(c);
});
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
google.visualization
var data = new google.visualization.arrayToDataTable(arr);
var options = {
title: 'Chess opening moves',
width: 800,
legend: { position: 'none' },
bars: 'vertical', // Required for Material Bar Charts.
axes: {
y: {
0: { side: 'top', label: 'Percentage'} // Top x-axis.
}
},
bar: { groupWidth: "100%" }
};
var chart = new google.charts.Bar(document.getElementById('top_x_div'));
chart.draw(data, options);
};
}});
}
It worked but only on first modal. When i try to open another modal i've got the follow error : google.charts.load() cannot be called more than once . How can i draw the chart using another callback, not 'setOnLoadCallback' ?
Your problem is that your function contain these two lines :
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);
This is wrong. google.charts.load() loads the google visualization API and setOnLoadCallback() is executed once when the API has finished loading. But you do not want to show the chart when google visualization is loaded, but when the user click a button (or whatever) to show a modal. So remove setOnLoadCallback completely and move load() out to the global scope - simply call drawStuff() manually from the success handler :
google.charts.load('current', {'packages':['bar']});
function inter(id) {
var arr = [
['Album', 'Vizualizari']
];
$.ajax({
url: 'popular.php',
type: 'GET',
dataType: 'json',
success: function(json) {
$.each(json, function(i, value) {
var c = [value.title, value.popular];
arr.push(c);
});
drawStuff(arr);
})
})
function drawStuff(arr) {
var data = new google.visualization.arrayToDataTable(arr);
var options = {
title: 'Chess opening moves',
width: 800,
legend: {
position: 'none'
},
bars: 'vertical', // Required for Material Bar Charts.
axes: {
y: {
0: {
side: 'top',
label: 'Percentage'
} // Top x-axis.
}
},
bar: {
groupWidth: "100%"
}
};
var chart = new google.charts.Bar(document.getElementById('top_x_div'));
chart.draw(data, options);
}
}
I m trying to figure it out that is it possible to make the json data fetched dynamically from a database with the help of php and mysql and can be plotted with highcharts that too dynamic auto updating? Any help would be appreciated.
following the code i have tried and is not working properly and want to implement to the the website for 10 lines.
<HTML>
<HEAD>
<TITLE>highchart example</TITLE>
<script type="text/javascript"src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script type="text/javascript">
var chart;
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 2
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData1, 1000);
},
cache: false,
});
}
function requestData1() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series2 = chart.series[1],
shift = series2.data.length > 20; // shift if the series is
// longer than 20
// add the point
chart.series[1].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false,
});
}
$(function () {
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis:
{
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: '',
margin: 80
}
},
series: [
{
name: 'Random data',
data: []
},
{
name: ' hahaha',
data: []
}
],
});
});
});
</script>
</HEAD>
<BODY>
<div id="container"
style="min-width: 728px; height: 400px; margin: 0 auto"></div>
</BODY>
</HTML>
*** the live-server-data.php is as followed:
<?php
// Set the JSON header
header("Content-type: text/json");
// The x value is the current JavaScript time, which is the Unix time multiplied
// by 1000.
$x = time() * 1000;
// The y value is a random number
$y = rand(48,52);
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>
You can try with
var options = {
chart: {
renderTo: 'chart',
},
credits: {
enabled: false
},
title: {
text: 'Impression/Click Overview',
x: -20
},
xAxis: {
categories: [{}]
},
tooltip: {
formatter: function() {
var s = '<b>'+ this.x +'</b>';
$.each(this.points, function(i, point) {
s += '<br/>'+point.series.name+': '+point.y;
});
return s;
},
shared: true
},
series: [{},{}]
};
$.ajax({
url: "json.php",
data: 'show=impression',
type:'post',
dataType: "json",
success: function(data){
options.xAxis.categories = data.categories;
options.series[0].name = 'Impression';
options.series[0].data = data.impression;
options.series[1].name = 'Click';
options.series[1].data = data.clicks;
var chart = new Highcharts.Chart(options);
}
});
The highcharts website has some useful articles about working with dynamic data. That is probably the best place to start.
http://www.highcharts.com/docs/working-with-data/preprocessing-live-data
http://www.highcharts.com/docs/working-with-data/preprocessing-data-from-a-database
Try something out, and if you have trouble, come back here with a more specific question showing what you have tried. As it stands, your question is too broad, and will probably get closed.
An ajax request for updating data looks something like:
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is // longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
index.html:
Function drawChart() {
var jsonData = $.ajax({
url: "server.php",
dataType: "json",
async: false
}).responseText;
var obj = jQuery.parseJSON(jsonData);
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: 'Number of visitors / <?php echo $unit; ?>'
};
var chart = new google.visualization.BarChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
}
server.php:
$SQLString = "SELECT (...)'".$_POST['value']."' (...)
$result = mysql_query($SQLString);
(...)
$data[$i] = array(...)
echo json_encode($data);
So, index.html get data from server.php right?
Can I send some values to server.php which are important to do the query before index.html do the jsonData...etc? How?
Thanks :)
Example of a query parameter:
var jsonData = $.ajax({
url: "server.php?someQuery=" + query,
dataType: "json",
async: false
}).responseText;
You can send using post method via ajax. Here is a JQuery example:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
http://api.jquery.com/jQuery.ajax/
you can use a library that will do it automatically for you, using phery http://phery-php-ajax.net, in your case it would be:
the event phery:json will deal with the JSON sent from the server
var remote = phery.remote('data', {'argument': 'you want to send'}, {'target':'server.php'}, false);
remote.bind('phery:json', function(event, obj){
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: 'Number of visitors / <?php echo $unit; ?>'
};
var chart = new google.visualization.BarChart(
document.getElementById('chart_div'));
chart.draw(data, options);
});
remote.phery('remote'); // call the remote AJAX function
in your server.php
function data($data){
$r = new PheryResponse;
// $data['argument'] will have 'you want to send'
$SQLString = "SELECT (...)'".$_POST['value']."' (...)"
$result = mysql_query($SQLString);
(...);
$data[$i] = array(...);
return $r->json($data);
}
Phery::instance()->set(array(
'data' => 'data'
))->process();