Javascript Pie Chart php to javascript object array - php

I am using the code at http://jsfiddle.net/MX7JC/9/ to build a pie chart.
But I want the data to come from php variables. How do I change :
var agg = { label: 'Aggressive', pct: [60, 10, 6, 30, 14, 10] },
as seen in the code on the link, so that pct consists of an array of php variables rather than fixed numbers. Such as :
var agg = { label: 'Aggressive', pct: [$r1, $r2, $r3, $r4, $r5, $r6]},
How do I alter the code to allows this? I tried json encode and I am having problems.

You can generate the Javascript when it's defined using PHP:
<script type="text/javascript">
var agg = { label: 'Aggressive', pct: [
<?php echo $r1.", ".$r2.", ".$r3.", ".$r4.", ".$r5.", ".$r6; ?>
]},
</script>

Related

chartJS or/and php print_r not working together

So, i want to input data for the bar chart from a database, i got everything figured out, but something does not work...
Here's a part of the view file,
var barChartData = {
labels : {{print_r($action_names, true)}} ,
datasets: [
{
label : 'Electronics',
fillColor : 'rgba(2, 24, 222, 1)',
strokeColor : 'rgba(2, 24, 222, 1)',
pointColor : 'rgba(2, 24, 222, 1)',
pointStrokeColor : '#c1c7d1',
pointHighlightFill : '#fff',
pointHighlightStroke: 'rgba(2, 24, 222, 1)',
data : {{print_r($action_count,true)}}
}
]
}
this does not work, it displays a blank chart.
The output from {{print_r($action_names, true)}} is ["OBJECT1","OBJECT1","OBJECT3"]
and the output of {{print_r($action_names, true)}} is [1,2,3]
in the exact same formatting, now, if i just post the values in, as text, it works, the chart appears just fine, but when i use the variable, nothing - blank. I need to use the variable, because the database from which i fetch the data, is gonna change quite frequently.
You can simply use implode() function to print your array data,
labels : [
{{implode(",", $action_names)}}
]
&
data : [
{{implode(",", $action_count)}}
]
you can't to put a php function like this
labels : {{print_r($action_names, true)}}
...
data: {{print_r($action_count,true)}}
try to isolate in a var
labels : { {$action_names} }
...
data: { {$action_count} }
Define new javascript array from existing php array using following syntax:
var labelValues = [<?php echo '"'.implode('","', $php_array).'"' ?>];
When you want to use the data in a script or something like that, you have to escape it, basically don't use {{something}} but use {!!something!!}

Load data from Google Analytics in a Chart.js chart

My question is: How do I load data from Google Analytics in a Chart.js chart?
I am writing a program with the Laravel framework (version 5.6) and use the Google Analytics API (not the Google Analytics Embed API)(version 3).
I get the data correctly presented in an array but I want to show it in a graph.
Subquestion: Do I need to replace the data in datasets with a connection to the Google Analytics API?
A simple chart from Chart.js:
<canvas id="userChart"></canvas>
<script>
var ctx = document.getElementById('userChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ["dag 1", "dag 8", "dag 15", "dag 22", "dag 30"],
datasets: [{
label: "users",
//backgroundColor: '#2f5ec4',
borderColor: '#2f5ec4',
data: [138, 163, 115, 124, 49],
}]
},
// Configuration options go here
options: {}
});
Update:
Example of how I get the Analytics data:
Route::get('/datatest', function()
{
$analyticsData =
Analytics::fetchTotalVisitorsAndPageViews(Period::days(30));
dd($analyticsData);
});
Example of the DD array:
It might be too late but for anyone who is in need, try the following. For your case you have your $analyticsData collection, which is a good start. Chartjs uses lists to map and compare data.
So for example we want to see a chart of date vs visitors
//transfer all of this code out of the routes to your controller
$analyticsData = Analytics::fetchTotalVisitorsAndPageViews(Period::days(30));
//send these two variables to your view
$dates = $analyticsData->pluck('date');
$visitors = $analyticsData->pluck('visitors');
In your script, the labels should receive $dates in a list as follows;
labels: {!! json_encode($dates) !!},
And data in datasets receive $visitors as a list;
data: {!! json_encode($visitors) !!}
See this article on my website for more in-depth explanations.

Unable to draw google Line Chart with Multiple columns with different data types

I am facing issues while implementing multi-line google chart. While plotting the line chart I am getting "All the series on given axis must be of the same data type".
Below is my Google line chart code snippet and I am fetching the values of frmyear, toyear and makes from database.(It is dynamic drop-down list).
function drawChart(frmyear, toyear, makes)
{
alert('hiii');
console.log(makes);
$_token = "{{ csrf_token() }}";
var jsondata = '';
$.ajax({
type: 'POST',
url: 'salesone',
data: {frmyear: frmyear, toyear: toyear, makes: makes, _token: $_token },
}).success(function(data) {
}).done(function(data){
jsondata = JSON.stringify(data);
console.log(jsondata);
drawgraph(jsondata);
})
.fail(function(data) {
alert( "error" );
});
}
function drawgraph(jsondata)
{
var data = new google.visualization.DataTable(jsondata);
var options = {
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, {width: 200, height: 300});
chart.draw(data, options);
}
If user select two brands e.g. Mahindra & Hyundai for duration of Jan 2011 to June 2011 then my JSON data looks like below:
{"cols":[{"label":"Datetime","type":"date"},{"label":"Make","type":"string"},{"label":"Sales","type":"number"}],"rows":[{"c":[{"v":"Date(2011, 0, 31)"},{"v":"Hyundai"},{"v":28989}]},{"c":[{"v":"Date(2011, 1, 28)"},{"v":"Hyundai"},{"v":31405}]},{"c":[{"v":"Date(2011, 2, 31)"},{"v":"Hyundai"},{"v":30529}]},{"c":[{"v":"Date(2011, 3, 30)"},{"v":"Hyundai"},{"v":30522}]},{"c":[{"v":"Date(2011, 4, 31)"},{"v":"Hyundai"},{"v":30076}]},{"c":[{"v":"Date(2011, 5, 30)"},{"v":"Hyundai"},{"v":29461}]},{"c":[{"v":"Date(2011, 0, 31)"},{"v":"Mahindra"},{"v":16620}]},{"c":[{"v":"Date(2011, 1, 28)"},{"v":"Mahindra"},{"v":14523}]},{"c":[{"v":"Date(2011, 2, 31)"},{"v":"Mahindra"},{"v":16044}]},{"c":[{"v":"Date(2011, 3, 30)"},{"v":"Mahindra"},{"v":14709}]},{"c":[{"v":"Date(2011, 4, 31)"},{"v":"Mahindra"},{"v":15892}]},{"c":[{"v":"Date(2011, 5, 30)"},{"v":"Mahindra"},{"v":15286}]}]}
Here I have three columns Datetime, Make & Sales and all are of different data types hence I am unable to plot Line chart for Hyundai & Mahindra.
I want the data in below format:
Date Hyndai Mahindra
Date(2011, 1, 28) 31405 16620
Date(2011, 2, 31) 30529 14523
Date(2011, 3, 30) 30522 16044
In this case either I have to create data view or I need to modify the JSON. But in both approaches I will not be aware of how many brands selected by user.
My application is in Laravel 5.1 & MySQL as Database. what is the possible solution available to plot the line graph using google charts in this scenario?

Pass existing php array to jquery

I have a PHP array I want to pass to my jquery (replace the test array with my php array).
Array
(
[12] => Some Text
[6] => Another text
[11] => one more text
)
Jquery:
$('#SearchUser').typeahead({
source: [
{ ID: 1, Name: 'Toronto' },
{ ID: 2, Name: 'Montreal' },
{ ID: 3, Name: 'New York' },
{ ID: 4, Name: 'Buffalo' },
{ ID: 5, Name: 'Boston' },
{ ID: 6, Name: 'Columbus' },
{ ID: 7, Name: 'Dallas' },
{ ID: 8, Name: 'Vancouver' },
{ ID: 9, Name: 'Seattle' },
{ ID: 10, Name: 'Los Angeles' }
],
display: 'Name',
val: 'ID',
itemSelected: updateID
});
So how can I set the var for "source" to my php array?
Suggestions?
As always,, you are awesome!
-Tom
How I'd done it in one of my projects was,
$.get("<?= $baseUrl ?>search/data", function (data) {
var dataObject = JSON.parse(data);
$('#q').typeahead({
'source': dataObject,
// 'items': 5
});
});
and my search controller's data method is:
echo (json_encode($arr)); // $arr is ["a","b","c"] etc. but you can have an associated array too.
Basically, the point of showing my code is to say use json
You can use json_encode function of php to conver a php array to json. Then you can use the json as javascript array.
http://www.php.net/manual/en/function.json-encode.php
I don't know how you get data from php code to javascript code, but if you print data as json, you can take it via an ajax call.
Use PHP's json_encode() function to create a string that is a valid JSON, and then read that with jQuery's $.getJSON().
Something like this:
get_array.php
$someArray = /* whatever */;
echo json_encode($someArray);
read_array.js
$.getJSON('get_array.php', function(data) {
// data now contains your array
});
Alternatively, you could do something like this:
<script type="text/javascript">
var someArray = <?php echo json_encode($someArray); ?>
</script>
If you don't want the separate files and don't mind using a global variable for it.
You can do the following:
<script type="text/javascript">
var jsArray = <?php echo json_encode($phpArray); ?>
</script>
but it is a bad practice to mix language X with language Y.
Well, take a look at my answer to this post in which you can do the following in a better way:
Is echoing Javascript code condtionally based on server-side logic considered harmful?
Hope this helps :-)

Displaying currency in Google chart API

I am using Google chart API to display a line chart, but I need the numbers to show as currency. On the chart itself, I have been able to get the numbers to display like currency, but when the mouse hovers over a point and the dialog box displays, the number is not displayed as specified.
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(<?php echo $data; ?>);
var options = {
chartArea:{left:40,top:10},
pointSize: 6,
vAxis: {format:'$###,###,###.00'}, // Money format
legend: {position:'none'}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
As you can see from this image, the vertical column displayed on the left does use decimal points as specified using vAxis.format in the above code, but the dialog box does not show the decimals or the dollar sign (I added the dollar sign after the screen capture).
How can I get the number in the dialog box to display the same as the numbers in the left aligned vertical column?
I tried updating the PHP array I am using to populate the data into currency format there, but then the Google chart does not render since it is not a plain digit.
This is perfect format to Brazilian currency:
var formatter = new google.visualization.NumberFormat({decimalSymbol: ',',groupingSymbol: '.', negativeColor: 'red', negativeParens: true, prefix: 'R$ '});
formatter.format(data, 1);
Works fine whit dollar also, just change R$ to $
10500.5 stay 10.500,50, more prefix
10500 stay 10.500,00, more prefix
There's a format for specifying both the raw value and formatted value for a cell: when loading the value into the chart, rather than, e.g. addRow(['2012-08-31, 4]); it would be addRow(['2012-08-31', {v: 4, f: '$4.00'}]); More examples of that syntax are sprinkled through the docs but I couldn't find a good place to link to it. It shouldn't be too hard to change the method by which the $data object from your example is generated to include that formatting, but there are other formatting options too.
If you'd rather define that formatting in the JS for whatever reason, you can use a NumberFormatter.
Try this:
var formatter = new google.visualization.NumberFormat({pattern:'###,###'} );
formatter.format(data, 1);
Worked great for me. Found at:
Comma Separated Data in Google Visualisation API
Another option that I found very useful, and similar in concept to the arrayToDataTable() method is the JavaScript literal initializer syntax as follows:
var data = new google.visualization.DataTable(
{
cols: [
{id: 'date', label: 'Date', type: 'string'},
{id: 'parnter1', label: 'Partner A', type: 'number'},
{id: 'partner2', label: 'Partner B', type: 'number'}
],
rows: [
{ c: [{ v: '06/2012' }, { v: 12345, f: '$12,345' }, { v: 98765, f: '$98,765'}] },
{ c: [{ v: '07/2012' }, { v: 10123, f: '$10,123' }, { v: 123123, f: '$123,123'}] }
]
}
);
https://google-developers.appspot.com/chart/interactive/docs/datatables_dataviews

Categories