I'm using this script in my file to shown error "Uncaught SyntaxError: Unexpected token '<'" in console.
How I fix it?
Error is shown at the PHP tag which is defined in the script.
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart()
{
var data = google.visualization.arrayToDataTable([
['Car', 'Number'],
<?php
while($row = mysqli_fetch_array($result))
{
echo "['".$row["car"]."', ".$row["number"]."],";
}
?>
]);
var options = {
title: 'Percentage of branded Car Services',
//is3D:true,
pieHole: 0.4
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
Your while,
while($row = mysqli_fetch_array($result))
{
echo "['".$row["car"]."', ".$row["number"]."],";
}
the last echo will print a "," and this can generate your problem.
I recomand to build an array and then use echo with an implode().
You cannot place php inside javascript however you can echo javascript in php.
I try to appear some geographical data as points (spots) in a global map.When i run the code -in the browser- are appearded the statistical results as text , the global map but on the they are not appeared.Itis must noted that the main code was taken from the code which implement the piechart.In the follow lines i present the code:
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>plus2net.com : Pie chart using data from MySQL table</title>
</head>
<body >
<?Php
//
require "connection.php";// Database connection
if($stmt = $link->query("SELECT Nationality_Name,Count FROM nationality_arrivals")){
echo "No of records : ".$stmt->num_rows."<br>";
$php_data_array = Array(); // create PHP array
echo "<table>
<tr> <th>Nationality_Name</th><th>Count</th></tr>";
while ($row = $stmt->fetch_row()) {
echo "<tr><td>$row[0]</td><td>$row[1]</td></tr>";
$php_data_array[] = $row; // Adding to array
}
echo "</table>";
}else{
echo $link->error;
}
//print_r( $php_data_array);
// You can display the json_encode output here.
echo json_encode($php_data_array);
// Transfor PHP array to JavaScript two dimensional array
echo "<script>
var my_2d = ".json_encode($php_data_array)."
</script>";
?>
<div id="chart_div"></div>
<br><br>
<a href=https://www.plus2net.com/php_tutorial/chart-database.php>Pie Chart from MySQL database</a>
</body>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
<div id="chart_div"></div>
<br><br>
<a href=https://www.plus2net.com/php_tutorial/chart-database.php>Pie Chart from MySQL database</a>
</body>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {
'packages': ['geochart'],
// Note: you will need to get a mapsApiKey for your project.
// See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
});
google.charts.setOnLoadCallback(drawMarkersMap);
function drawMarkersMap() {
var data = google.visualization.arrayToDataTable([
['Nationality_Name','string'],['Count','number']
]);
var options = {title:'plus2net.com : How the tutorials are distributed',
width:600,height:500};
// Instantiate and draw the chart
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
}
</script>
</html>
So many question regarding javascript and so sorry about it. I have create yet a small chart which i promised one of the member/mentor here that I will study real hard in javascript.
So here I am creating a small yet perfect chart but the word perfect seems not fit for it for it returns a wrong display.
Here's the code for the php/html file with the ajax $.getJSON
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script src="canvasjs.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("data.php", function (result) {
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: result
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 380px;"></div>
</body>
</html>
Now here's the data to be pulled from database
So there are actually 5 types of dogs based on animal_id
LARGE,MEDIUM,SMALL,PUPPY,DISABLED
Now Here's the data.php
<?php
header('Content-Type: application/json');
$con = mysqli_connect("localhost","root","","siglo");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}else
{
$data_points = array();
$result = mysqli_query($con, "SELECT animal_id,FROM_UNIXTIME(microtime,' %M ') as microtimes, SUM(srp) as admitting_cost FROM vet_table WHERE microtime BETWEEN UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 180 day)) and 1480723199 GROUP BY telco_id, microtimes");
while($row = mysqli_fetch_array($result))
{
$point = array("label" => $row['microtimes'] , "y" => $row['admitting_cost'],);
array_push($data_points, $point);
}
echo json_encode($data_points, JSON_NUMERIC_CHECK);
}
mysqli_close($con);
?>
This is the result
I can't simply find where I went wrong and the result must be at the bottom is the months and then each month should have 5 bar corresponding to admitting cost
So let's say animal_id 091092010290192(sample) has accumulated 600 on august, 500 on september and on.....like that
Please help.
I've done quite a bit of searching and have found solutions for issues similar to my problem but nothing that has worked so far. Any help is appreciated.
I am attempting to create a Google Line Chart from data I am querying from my database and then parsing to JSON. My query and JSON looks good but when I insert it into the DataTable the web page is blank.
This the JSON output I have:
[["date","percentage"],["0000-00-00 00:00:00",28.18],["2015-01-06 06:00:01",93.65],["2015-01-07 06:00:01",85.9],["2015-01-08 06:08:43",89.25],["2015-01-09 06:08:42",99.26],["2015-01-10 14:50:37",99.48],["2015-02-06 06:00:01",93.88],["2015-02-07 06:00:01",89.15],["2015-02-08 06:08:51",89.55],["2015-02-09 06:09:25",98.94],["2015-02-09 17:26:50",98.94],["2015-02-10 06:10:55",99.06],["2015-03-07 06:11:32",85.7],["2015-03-08 06:07:58",89.86],["2015-03-10 06:11:04",99.06],["2015-04-06 14:19:26",82.17],["2015-04-07 06:11:47",85.8],["2015-04-08 06:10:01",89.76],["2015-04-10 06:10:53",100],["2015-05-06 16:25:01",91.21],["2015-05-07 06:11:12",85.7],["2015-05-08 06:08:53",89.25],["2015-05-09 22:35:40",97.77],["2015-05-10 06:10:39",99.17],["2015-05-10 21:28:01",98.85],["2015-06-06 06:00:02",90.84],["2015-06-07 06:11:05",85.9],["2015-06-09 06:09:32",97.88],["2015-06-10 06:10:55",99.79],["2015-07-06 06:00:01",91.33],["2015-07-07 06:10:35",85.09],["2015-07-08 06:09:36",89.45],["2015-07-09 06:08:55",98.2],["2015-07-10 06:12:44",5.94],["2015-08-06 06:00:01",91.58],["2015-08-08 06:09:03",89.05],["2015-08-09 06:09:23",97.03],["2015-08-09 15:54:27",97.67],["2015-09-06 06:00:01",90.96],["2015-09-07 06:12:33",84.99],["2015-09-08 06:08:54",89.15],["2015-09-09 06:12:48",99.26],["2015-09-09 14:29:39",95.02],["2015-10-06 06:00:01",91.09],["2015-10-07 06:13:13",89.35],["2015-10-08 06:08:42",89.25],["2015-10-09 06:09:40",99.47],["2015-10-09 17:14:20",99.47],["2015-11-05 06:00:01",97.41],["2015-11-06 06:00:01",85.47],["2015-11-07 06:12:17",89.45],["2015-11-08 06:10:45",89.45],["2015-12-05 06:00:01",96.7],["2015-12-06 06:00:01",90.72],["2015-12-07 06:12:22",88.74],["2015-12-09 06:09:39",99.58]]
When I insert this into the JSON Validator at https://jsonformatter.curiousconcept.com it says it is valid JSON and when I hard code it in everything seems to work..
Here is my code:
<?php
$dbhost="localhost";
$dblogin="root";
$dbpwd="password!";
$dbname="qaDB";
$db = mysql_connect($dbhost,$dblogin,$dbpwd);
mysql_select_db($dbname);
$SQLString = "SELECT date, percentage FROM reports WHERE RTYPE_ID=1";
$result = mysql_query($SQLString);
$num = mysql_num_rows($result);
# set heading
$data[0] = array('date','percentage');
for ($i=1; $i<($num+1); $i++)
{
$data[$i] = array(substr(mysql_result($result, $i-1, "date"), 0, 20),
(float) mysql_result($result, $i-1, "percentage"));
}
echo json_encode($data);
mysql_close($db);
?>
Here is the page to create the Google line chart.
<html>
<head>
<title>JSON Chart Test</title>
<!-- Load jQuery -->
<script language="javascript" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js">
</script>
<!-- Load Google JSAPI -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
// var newWin = window.open();
var jsonData = $.ajax({
url: "legacyDashboardJSON.php",
dataType: "json",
async: false
}).responseText;
//var newStr = jsonData.substring(1, jsonData .length-1);
//newWin.document.write(jsonData);
// var parsedData = JSON.parse(newStr);
//var obj = JSON.stringify(newStr);
var data = google.visualization.DataTable(jsonData);
var options = {
title: 'Stats'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div">
</div>
</body>
</html>
Thanks!
UPDATE Found the solution.
Here's the code:
<?php
$DB_NAME = 'qaDB';
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '!';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli->query('SELECT date,percentage FROM reports');
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'date', 'type' => 'string'),
array('label' => 'percentage', 'type' => 'number')
);
foreach($result as $r) {
$temp = array();
$temp[] = array('v' => (string) $r['date']);
$temp[] = array('v' => (int) $r['percentage']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
mysql_close($mysqli);
?>
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "legacyDashboardJSON.php",
dataType: "json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var options = {
title: 'Metrics',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--this is the div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
You need to provide a success function in your .ajax call that will execute when the data returns. Anything that needs the data should be placed inside this function, or passed from within the success function to another function. You could also use .done() on the end of your .ajax call and place the rest of your script in there.
I'm having trouble displaying Google Charts correctly. I'm trying to do this with Ajax and PHP.
This is the code that is loaded on the page:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type='text/javascript'>
// Dummy Array for now
<?php
$php_array = array(
array('Terms', 'Visits'),
array('test', 25),
array('joke', 25),
array('funny', 50),
);
//Convert the PHP Array into a Javascript Array
$js_array = json_encode($php_array);
echo "var arrTableData = ". $js_array . ";\n";
?>
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawCharts);
function drawCharts(){
// Each chart function
$.getJSON('charts_ajax.php',{'a' : 'terms', 'd' : arrTableData }, function(data){
if(data){
initGoogleChart(data)
}else {
console.log("There is no data coming back");
}
});
}
function initGoogleChart(data){
var tableData = google.visualization.arrayToDataTable(data);
var options = {
title: 'Title'
};
var chart = new google.visualization.PieChart(document.getElementById('terms-table'));
chart.draw(tableData, options);
}
</script>
and on the charts_ajax.php file there is this data:
<?php
if ($_GET['a'] == "terms") {
$arrTableData = $_GET['d'];
echo json_encode($arrTableData);
}
?>
This is what the Chart is outputting:
Can anybody shed some light on this and possible help me fix it please?
Have you tried converting the data into a Google Charts JSON format? Here's an example.
foreach($arrTableData as $r2) {
if(!isset($google_JSON2)) {
$google_JSON2 = "{\"cols\": [";
$column = array_keys($r2);
foreach($column as $key=>$value) {
$google_JSON_cols2[]="{\"id\": ".$key.", \"label\": \"".$value."\", \"type\": \"string\"}";
}
$google_JSON2 .= implode(",",$google_JSON_cols2)."],\"rows\": [";
}