I am having problems plotting my pie chart using jqplot.
After getting my results from php i have converted it to json using json_encode. The output is
{"a":2,"b":1,"c":5,"d":650}
Now when i try to put these results into my javascript
<script class="code" type="text/javascript">
$(document).ready(function(){
// method 1
//var data1 = document.getElementById("dataArray").value;
//eval('data1 = '+data+';');
// method 2
var data1 = <?php echo json_encode($data); ?>;
var plot1 = jQuery.jqplot ('Chart', [data1],
{
seriesDefaults: {
// Make this a pie chart.
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
// Put data labels on the pie slices.
// By default, labels show the percentage of the slice.
showDataLabels: true
}
},
legend: { show:true, location: 'e' }
}
);
});
</script>
I've tried two methods, the first to put it inside a hidden field, and the second to retrieve straight from PHP. Both of which result in Uncaught. No plot target specified errors in my Chrome console.
What is it I am doing wrong here?
Thanks guys.
As Asad mentioned, my stupid mistake was that Chart was not specified as an element. So yeah if anyone else ever comes into the same problem, be sure to check that out. :)
Related
I am going through all of our PHP (V7.3) pages and upgrading all charts to the latest version.
On some pages where the chart data is part of a sub page or created from an AJAX call I get this error all the time
Uncaught TypeError: Cannot read property 'axis' of undefined
at vo.parse (chart3.min.js:13)
at vo._insertElements (chart3.min.js:13)
at vo._resyncElements (chart3.min.js:13)
at vo.buildOrUpdateElements (chart3.min.js:13)
at oo.update (chart3.min.js:13)
at new oo (chart3.min.js:13)
at eval (eval at <anonymous> (jquery.min.js:2), <anonymous>:18:19)
at eval (<anonymous>)
at jquery.min.js:2
at Function.globalEval (jquery.min.js:2)
My code has changed from:
<canvas id='chart_canvas' width='620' height='300'></canvas>
<script>
var data = <?php echo json_encode($data); ?>;
var ctx = document.getElementById("chart_canvas").getContext("2d");
var myNewChart = new Chart(ctx).Line(data, {
pointHitDetectionRadius: 5
});
</script>
to this:
<canvas id='chart_canvas' width='620' height='300'></canvas>
<script>
var data = <?php echo json_encode($data); ?>;
const config = {
type: 'line',
data,
options: {
responsive: true,
}
};
var myChart = new Chart(
document.getElementById('chart_canvas'),
config
);
</script>
The data varialble is:
var data = {"labels":["2021-07-17","2021-07-18","2021-07-19","2021-07-20","2021-07-21","2021-07-22","2021-07-23","2021-07-24","2021-07-25","2021-07-26","2021-07-27","2021-07-28","2021-07-29","2021-07-30","2021-07-31","2021-08-01","2021-08-02","2021-08-03","2021-08-04","2021-08-05","2021-08-06","2021-08-07","2021-08-08","2021-08-09","2021-08-10","2021-08-11","2021-08-12","2021-08-13","2021-08-14","2021-08-15","2021-08-16","2021-08-17"],"datasets":[{"label":"Jobs Created","fillColor":"rgba(26, 188, 156,0.2)","strokeColor":"rgba(26, 188, 156,1)","pointColor":"rgba(26, 188, 156,1)","pointStrokeColor":"#fff","pointHighlightFill":"#fff","pointHighlightStroke":"rgba(26, 188, 156,1)","data":{"2021-08-17":"2"}}]};
I know the code is ok because I have tried it in https://playcode.io/
I just cannot understand the error message and there is nothing i have found on Google, appreciate any pointers.
In your data you only have 1 item. This will be very hard to see on the chart because there will be no line to draw between items.
Adding to that, the data in your datasets should be formatted like this.
It looks like you are trying to combine Primitive and Object styles when you should be using either one. Because you are already giving labels, you only need to give the data like this: [10, 20, 30]
you can also give the data like you currently are giving. You just don't need the labels.
found the culprit - prototype-1.7.js
removed it and all works perfectly
I am using an ajax function to get data for rendering Google Pie chart and loading those data in javascript but some how the Pie chart is not rendering but when i hard code the AJAX output into javascript pie chart function it does render perfectly. Below is my code can any one tell me what's wrong? thank you for your help.
<?php
$sales_data = koolajax.callback(get_asin_repo($asin,$sku));
?>
JS here:
// AJAX Output is ['POS', 'Sold This Month'],['AZN CG UK',893],['AZN JT UK',449],['AZN PT UK',1349]
alert($sales_data);
//var data = google.visualization.arrayToDataTable([$sales_data]);//This doesn't work
//This Works
var data = google.visualization.arrayToDataTable([['POS', 'Sold This Month'],['AZN CG UK',893],['AZN JT UK',449],['AZN PT UK',1349]]);
var options = {
title: 'Statistics For '+$asin
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div1'));
chart.draw(data, options);
it Was really simple. all i need to do was get data from DB in JSON format and pass it in
var data = new google.visualization.DataTable($sales_data);
function instead of
var data = google.visualization.arrayToDataTable([$sales_data])
And it works.
Thank you all for your support and time...........
You must check the kind of variable returned from server and pack it in way that GoogleChart understands.
In your case, you requested that google.visualization.arrayToDataTable to create a DataSource instance for you. But that static method also requires that YOU follow this rule:
This method takes in a 2-dimensional array and converts it to a
DataTable. See the
Google Charts Documentation
So make a check before calling that routine.
if ( $sales_data instanceof Array )
{
var willWork = [];
var entry;
while ( $sales_data.length )
{
entry = $sales_data.shift();
if ( !(entry instanceof Array) || entry.length < 2 )
window.alert( 'Incorrect server return. Call support.' );
willWork.push( entry );
}
}
else
window.alert( 'Incorrect server return. Call support.' );
Google pie chart get data from PHP
I have been searching since 4 hours how to populate data from PHP to google pie chart but not found any solution, actually, my data format was wrong in PHP.
You can prepare data in PHP using this way:
function yourFunction(){
$data = array();
$data[0] = array("Status", "Revenue");
$data[1] = array('Pending', 500);
$data[2] = array('Confirmed', 1000);
$data[3] = array('Payable', 3000);
return json_encode($data );
}
Parse data on frontend:
var obj = JSON.parse(data);
var data = new google.visualization.arrayToDataTable(data);
I am attempting to make a pie chart using a php file that gets the information from MySQL, JSON encodes it, and then sends it to my JS file to make the pie chart. I have looked at most of the other questions posted here and none of them help me at all. I have attempted to re-qrite my code to match ones that seem to fit, but nothing is working.
My php file is:
$shelvDate = $_POST['shelvDate'];
$x = 0;
// get information from database for shelving chart
$shelv = $conn -> query ("SELECT sum(quantity) as qty, date_process, created_by, first_name from inventory LEFT JOIN users on users.user_id =inventory.created_by
WHERE date_process = '$shelvDate' GROUP BY created_by" );
$num_rows = $shelv->num_rows;
if($num_rows > 0){
while($row = $shelv->fetch_assoc()) {
if($row['qty'] > 0){
$qtyArray[$x] = $row['qty'];
$nameArray[$x] = $row['first_name'];
}
$x++;
$pairs = array('first_name' => $nameArray, 'qty' => $qtyArray);
} // end of while statement
} //end of if statement
$conn->close();
echo json_encode(array($pairs));
When I attempt to get the data into my ajax/js I get an error. My JS is:
$("#getRecords").live('click', function() {
var ajaxDataRenderer = function(url, plot, options) {
var ret = null;
$.ajax({
type: "POST",
async: false,
url: url,
dataType:"json",
data: ({shelvDate: $('#shelvDate').val()}),
success: function(data) {
for(var x=0; x<data.first_name.length; x++) {
var info = [data.first_name[x], data.qty[x]];
ret.push(info);
}
}); // end of ajax call
return ret;
}; // end of ajaxDataRenerer call
// The url for our json data
var jsonurl = "shelvChart.php";
var plot2 = $.jqplot('shelvChart', jsonurl,{
seriesDefaults: {
// Make this a pie chart.
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
// Put data labels on the pie slices.
// By default, labels show the percentage of the slice.
showDataLabels: true
}
},
title: "Books Shelved",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
});
});
I am don't know what I'm doing wrong or even where to go from here as I am still new to AJAX and JS. Any help will be greatly appreciated.
Jim
It would be very useful to see a real JSON string you are getting, cause I am not sure how you can get name[object,object],qty[object,object] after calling alert(ret) or maybe you are referring to other alert?.
Anyway from what you are saying your problem is that you must make sure that the array returned by the ajaxDataRenderer function is of a proper format that is accepted by a pie chart.
Therefore, for example, inside your PHP or JavaScript code you need to make sure that the returned array ret is of the following format:
ret = [[name[0], qty[0]], [name[1], qty[1]], ...];
This way all values that are in name array will be used as labels and qty array will be used as values from which the percentage will be evaluated.
Similar approach that shows how to prepare data for a chart is shown in this answer.
As the title says, I have slickgrid getting/parsing JSON data from PHP, but while I can get it to update to the proper row count, nothing is displayed in a cell unless I edit it first. When I do, the correct data is displayed, but only for cells I have edited. Here is the relevant code:
$(function () {
$.getJSON("./test3.php", function(jsondata) {
$.each(jsondata, function(i, arr) {
var d = (data[i] = {});
$.each(arr, function(key, value) {
d[key] = value;
});
});
grid.updateRowCount();
grid.render();
});
grid = new Slick.Grid("#myGrid", data, columns, options);
//continues function prepping the grid
You might want to go for simpler implementation, there's no need to loop through all your data just dump your "jsondata" directly inside the SlickGrid Object creation.
As long as you have the "data" array into a JSON Object then you're fine. Something like this:
{ "data":[{"id":"84","name" : "Someone" ... ]}
// then pass it to your Slick Object.
grid = new Slick.Grid("#myGrid", jsondata, columns, options);
That's all... Oh and don't forget to have at least have a unique "id" on all rows
You can see example from this web site:
http://joeriks.com/2011/07/03/a-first-look-at-slickgrid-with-read-and-update-in-webmatrix/
I needed to call grid.invalidateRow() on all of the added rows.
I'm trying to read in values from a db using php (mySQL) then have them show on a graph in flot. I know the values are read in correctly and I'm not getting any errors but the graph won't show.
Little help?
Thanks in advance.
<?php
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$graphdata[] = array( (int)$row[0], (int)$row[1] );
}
?>
/////
<div id="placeholder" style="width:600px;height:300px"></div>
<script language="javascript" type="text/javascript">
var dataset1 = <?php echo json_encode($graphdata);?>;
var data = [
{
label: "Random Values",
data: dataset1
}
];
var plotarea = $("#placeholder");
$.plot( plotarea , data);
</script>
The contents of your pastebin show that the JSON string you're outputting is invalid JSON.
var data = [{ label: "Random Values",data: dataset1}];
will validate if it's changed to:
var data = [{"label": "Random Values","data": "dataset1"}]
That's just an example, but I suspect that Flot is looking for a slightly different format, so you'll have to verify exactly what they're looking for against their documentation. I'm going through the same exercise right now with FusionCharts, so I'm feeling your pain. jsonlint.com is your friend on this one, output your JSON and verify it frequently. I'd also recommend that to initially get it working, start with just a string of JSON (even one that you copy from their examples) that you put right in your code. Get the chart working first, then work on getting your PHP to duplicate the example JSON string separately.
Try delaying creating the graph until the DOM is loaded:
jQuery(document).ready(function ($){
var plotarea = $("#placeholder");
$.plot( plotarea , data);
});