as the title saying im getting this error when trying to get charts inside function in another file like this
functions.php
function get_likes($catid){
require dirname (__FILE__).'/dbfunction.php';
?>
<script type="text/javascript" src="../assets/js/charts_min.js"></script>
<script type="text/javascript" src="../assets/js/functions.js"></script>
<?php
/// myquery here fetching the likes from database
?>
<script>
google.charts.load('current', {'packages':['corechart']});
</script>
<?php
if ($polls->execute()) {
while ($row = $polls->fetch(PDO::FETCH_ASSOC)) {
?>
<script>
a= <?php echo 2; ?> ;
b= <?php echo 3; ?> ;
c= <?php echo 5; ?> ;
i= <?php echo $row['id']; ?> ; ///// this i is looped to id 31 and 32
google.charts.setOnLoadCallback(function() { drawChart(a,b,c,i)}); ////But this didnt loop and it prints one chart for id 31. Because when i make alert(i) inside drawChart it alerts two times 31 and 31 .
</script>
<?php
echo "<div id="Votes_container"></div>";
}
}
my functions.js
function drawChart(a,b,c,i) {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['do', a],
['ri', b],
['me', c]
]);
// Set chart options
var options = {'title':'',
'width':500,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('Votes_container'+i));
chart.draw(data, options);
}
my index.php
require 'includes/functions.php';
$id = 1 ;
get_likes($catid) ;
So when i load index.php i want to get charts which gets data from database and come with get_likes() function , but my try didnt realise and it throws the error in the title .
where did the mistake located . Please ask me if i forget something before downvoting :) .
thanks for the help .
EDIT: i have edited the id of the divs where it should load the charts but it doesnt work either and same error.
Edited as the comment suggested and it prints the chart but its not looped now throw all ids.
Last Edit : this edit im writing how it worked for me.
I had to declare variables inside the function ,
google.charts.setOnLoadCallback(function() {
a= <?php echo 2; ?> ;
b= <?php echo 3; ?> ;
c= <?php echo 5; ?> ;
i= <?php echo $row['id']; ?> ;
drawChart(a,b,c,i)});
Related
I want to display data from the controller and throw it in the view as a dataset, but I have trouble how to write a loop on scriptjava.
This is the code that I have tried, and still fails
This my controller :
laravel
$query = DB::table('app_history_calls')
->SELECT(DB::raw("(MONTH(date)) as bulan"))
->GROUPBY('date',DB::raw("MONTH(date)"))
->ORDERBY('date','asc')->get();
return view('dashboard.index',compact('query'));
}
and this my view:
laravel
<script type="text/javascript">
var month= [
<?php foreach ($query as $bulan): ?>
<?php echo (string)$bulan ?>
<?php endforeach; ?>
];
</script>
I expected the result will be like this:
"var month= [1,2,3,4,5,6,7,8,9,10,11,12];"
So that it can be read on the dataset
$data['query'] = DB::table('app_history_calls')
->SELECT(DB::raw("(MONTH(date)) as bulan"))
->GROUPBY('date',DB::raw("MONTH(date)"))
->ORDERBY('date','asc')->get();
return view('dashboard.index')->withdata($data);
}
<script type="text/javascript">
var month= [
<?php foreach ($data['query'] as $bulan): ?>
<?php echo (string)$bulan ?>
<?php endforeach; ?>
];
</script>
Replace above code with your code i passed value in $data array and in for loop read $data['query'] in js
I am trying to show fetched data in Google charts, but PHP variables inside the javascript are not echoed.. If I echo variables outside of the javascript all works fine, so I suspect that something must be wrong in my javascript.. I double-checked everything but I can't figure our where is the issue..
The code does not show any errors!
This is the output in browser source..
['Active Posts',$post_counts],['Categories',$category_counts],['Users',$user_counts],['Comments',$comment_counts],
Any suggestion?
Thank you
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Data', 'Count'],
<?php
$data_text = ['Active Posts', 'Categories', 'Users', 'Comments'];
$data_count = ['$post_counts', '$category_counts', '$user_counts', '$comment_counts'];
for($i = 0; $i < 4; $i++) {
echo "['$data_text[$i]'" . "," . "$data_count[$i]],";
}
?>
]);
var options = {
chart: {
title: '',
subtitle: '',
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
</script>
Since you're already using PHP to output data for JS, you can just use json_encode to convert your ARRAY to JSON data.
<?php
$data = [
'Data' => 'Count',
'Active Posts' => $post_counts,
'Categories' => $category_counts,
'Users' => $user_counts,
'Comments' => $comment_counts
];
$json = json_encode($data);
?>
var data = google.visualization.arrayToDataTable("<?php echo $json; ?>");
Remove quotes from php variables,
Use this,
$data_count = [$post_counts, $category_counts, $user_counts, $comment_counts];
instead of,
$data_count = ['$post_counts', '$category_counts', '$user_counts', '$comment_counts'];
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);
}
I've been trying to retrieve data from mysql database using SELECT Count, as I got a list of countries which I want to count how many times each country is displayed in the column SovereignState, to a Google Geo Chart and by browsing around, I believe that json_encode should do the trick.
However, I have no idea how to get make a json_encode from my php code and then put it in the DataTable of the chart.
This is the php code:
define('DB_NAME', '');
define('DB_USER', '');
define('DB_PASSWORD','');
define('DB_HOST', '');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) ;
if ($conn->connect_error) {
die ('Could not connect: ' . $conn->connect_error);
}
$sql = "SELECT SovereignState, COUNT(*) FROM Data_2 GROUP BY SovereignState";
echo $sql;
//$result = $conn->query($sql);
$result = $conn->multi_query($sql);
if(!$result) {
echo "Could not successdully run query ($sql) from DB: " . mysql_error(); exit;
}
echo "<pre>";
do {
if ($result = $conn->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s - %s\n", $row[0], $row[1]);
}
$result->free();
}
} while ($conn->more_results());
echo "</pre>";
$conn->close();
And this is the html code of the google geochart:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["geochart"]});
google.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Number'],
]);
var options = {};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
</script>
You can use json_encode() from your PHP code and use Ajax in order to get the JSON into your JS code.
Also, (not recommended) you can just call a PHP function from your JS code with <?php myFunction();?>, that function should return an echo json_encode().
I'm strugling getting data from PHP into a graph. I have the following pieces of code on 1 php page. First the simple part:
$sql = "SELECT * FROM (SELECT timestamp, CurrentKelvin, TargetKelvin, WeatherTempKelvin FROM `rawdata` ORDER BY `rawdata`.`timestamp` DESC LIMIT 10) AS ttbl ORDER BY `timestamp` ASC;";
$results = mysqli_query($con,$sql);
$ChartData = array();
foreach($results as $result)
{
$ChartData[] = array( (int)$result['CurrentKelvin'],(int)$result['TargetKelvin']);
}
$ChartData = json_encode($ChartData);
Then the javascript part:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'CurrentKelvin');
data.addColumn('number', 'TargetKelvin');
alert( <?php echo json_encode($ChartData); ?>);
data.addRows( <?php echo json_encode($ChartData); ?> );
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data);
}
</script>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
When i run the above the alert command shows the following output:
[[292,290],[292,290],[291,290],[291,290],[291,290],[291,290],[291,290],[291,290],[291,290],[291,290]]
But the data.addRows line generates the following error:
Error: Argument given to addRows must be either a number or an array
Changing the data.addRows to something simple (and changing data.addColumn to string, with the same array construction, I do get a graph:
data.addRows([
['Ivan', 5],
['Igor', 7],
['Felix', 8],
['Bob', 4]
]);
I just can't figure out what is going wrong. Any help is appreciated.
Answer given by Dinesh worked:
var json_arr = <?php echo json_encode($ChartData); ?>;
data.addRows(JSON.parse(json_arr));