Filling ammap using mysql - javascript

I'm not that experienced in Javascript and I'm kind of stuck with ammap (http://www.amcharts.com/javascript-maps/).
The idea is to add some locations to the map from a mysql database. Their tutorial chapter on this is outdated and recommends using the DataLoader plugin instead (http://www.amcharts.com/tutorials/using-data-loader-plugin/). This, however, is for amcharts rather than ammap, and I can't figure it out.
Here's the code:
index.php
<script src="ammap/ammap.js" type="text/javascript"></script>
<link rel="stylesheet" href="ammap/ammap.css" type="text/css"
media="all" />
<script src="ammap/maps/js/germanyLow.js" type="text/javascript"></script>
<script
src="http://www.amcharts.com/lib/3/plugins/dataloader/dataloader.min.js"
type="text/javascript"></script>
<script type="text/javascript">
AmCharts.makeChart( "mapdiv", {
"type": "map",
"dataProvider": {
"map": "germanyLow"
}
"dataLoader": {
"url": "data.php",
"format": "json",
"showErrors": true
},
} );
</script>
<div id="mapdiv" style="width: 600px; height: 400px;"></div>
data.php
<?php
$server = "localhost";
$user = "root";
$pass = "";
$db = "map";
$conn = new mysqli ( $server, $user, $pass, $db);
if ($conn->connect_error) {
die ( "Connection failed: " . $conn->connect_error );
}
$sql = "SELECT latitude, longitude FROM map";
$result = $conn->query($sql);
if($result->num_rows > 0){
$data = array();
while($row = $result->fetch_assoc()){
$data[] = $row;
}
}else{
//
}
$string = json_encode($data);
echo $string;
?>
The json string of the data.php file is:
[{"latitude":"48.47","longitude":"9.11"},{"latitude":"53.33","longitude":"10"}]
The map won't load with this code. If I comment out the dataLoader part, the map itself loads just fine. Does anybody know how to use the dataLoader properly? Any help would be greatly appreciated.

Solved with help from amcharts support crew. For those of you interested in the solution:
AmCharts.makeChart("mapdiv", {
"type": "map",
"data": {
"map": "germanyLow"
},
"dataLoader": {
"url": "data.php",
"format": "json",
"showErrors": true,
"postProcess": function(data, config, map) {
// create a new dataProvider
var mapData = map.data;
// init images array
if (mapData.images === undefined)
mapData.images = [];
// create images out of loaded data
for(var i = 0; i < data.length; i++) {
var image = data[i];
image.type = "circle";
mapData.images.push(image);
}
return mapData;
}
}
});

Related

PHP with Javascript, both working code - combined cannot be displayed

I have 2 pieces of working code. This first is slightly convoluted but it brings me back the location I need.
<?php
$ider = $_GET['id'];
$host = "localhost";
$user = "Meh";
$password ="pass";
$database = "MyDB";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
echo 'Error';
}
$sql = "SELECT id, Location FROM MyDB WHERE id =$ider";
$result = $connect->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$thisloc = $row["Location"];
}
} else {
echo "0 results";
}
$conn->close();
?>
Now I want to use this info on a lil google api javascript boyo with multiple markers.
<html>
<head>
<title>Custom Markers</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 90%;
width: 70%
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(
document.getElementById('map'),
{center: new google.maps.LatLng(62.009094, -7.316163), zoom: 13});
var iconBase =
'https://developers.google.com/maps/documentation/javascript/examples/full/images/';
var iconBase2 =
'http://icons.iconarchive.com/icons/paomedia/small-n-flat/32/';
var icons = {
equipment: {
icon: 'http://icons.iconarchive.com/icons/icons-land/vista-map-markers/32/Map-Marker-Marker-Outside-Azure-icon.png'
},
library: {
icon: iconBase2 + 'map-marker-icon.png'
},
info: {
icon: iconBase + 'info-i_maps.png'
}
};
var dormant = 'equipment';
var active = 'library';
var later = 62.013376;
var longer = -7.307036;
var features = [
{
position: new google.maps.LatLng(62.018596, -7.292223),
type: dormant
}, {
position: new google.maps.LatLng(62.013376, -7.307036),
type: dormant
}, {
position: new google.maps.LatLng(62.009094, -7.316163),
type: dormant
}, {
position: new google.maps.LatLng(62.990540, -7.318134),
type: dormant
}, {
position: new google.maps.LatLng(62.005287, -7.309028),
type: dormant
}, {
position: new google.maps.LatLng(later, longer),
type: active
}
];
// Create markers.
for (var i = 0; i < features.length; i++) {
var marker = new google.maps.Marker({
position: features[i].position,
icon: icons[features[i].type].icon,
map: map
});
};
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=mykey&callback=initMap"> >
</script>
</body>
</html>
As you can see i'm not a very sophisticated programmer. More of a junkyard dog.
There's a lot going on there - but I'm in the middle of a few changes and I need the info for testing.
Both scripts just won't seem to work together, page cannot be displayed. Am I going about this the right way? Any advice would be great.
if database has Names of places instead of coordination try Using this API instead
https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=<?php echo$thisloc;?>&inputtype=textquery&fields=photos,formatted_address,name,geometry&key=YOUR_API_KEY
After taking the advice of #Rkv88 - Kanyan and a long day of troubleshooting, I managed to isolate the problem. It was actually the PHP. Weirdly when I echoed a result it would display the output, but with no echo it caused - Page cannot be displayed.
Anyways
I just rewrote the PHP script to what I needed. It's probably not the most sophisticated thing in the world. But I only need a specific value every time
<?php
$ider = $_GET['id'];
$conn = mysqli_connect("localhost", "meh", "pass", "MyDB");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Location FROM LifeSaver1 WHERE id =$ider";
$result = $conn->query($sql);
$obj = mysqli_fetch_object($result);
$obj2 = $obj->Location;
?>

How to pass variable from controller to ajax request in view and then retrieve it in php script (codeigniter)

Hello I want to pass this variable: ID_person to view and then send it to php script to get requested data from database.
Controller:
public function view($id){
$data = array();
if(!empty($id)){
$data['zakaznici'] = $this->Zakaznici_model->getRows($id); //$data['temperatures'] = $this->Temperatures_model->getRows($id);
$data['title'] = 'Údaje o zákazníkovi';
$data['ID_person'] = $id;
$this->load->view('zakazniciview', $data);
}else{
redirect('/zakaznici');
}
}
So far I'm using this request in my view:
<script type="text/javascript">
$(function() {
$.ajax({
url: "http://localhost/skolaa/chart_vypozicky.php",
type: "GET",
success: function(data) {
chartData = data;
var chartProperties = {
caption: "Celková suma za prenájmy počas jednotlivých rokov",
xAxisName: "Rok",
yAxisName: "Suma ",
rotatevalues: "0",
useDataPlotColorForLabels: "1",
theme: "fusion"
};
apiChart = new FusionCharts({
type: "column2d",
renderAt: "chart-container",
width: "550",
height: "350",
dataFormat: "json",
dataSource: {
chart: chartProperties,
data: chartData
}
});
apiChart.render();
}
});
});
</script>
It is working but I need to get somehow that ID_person variable from controller and sent it to chart_vypozicky.php script and then retrieve it in query in this script.
Php script:
<?php
//address of the server where db is installed
$servername = "localhost";
//username to connect to the db
//the default value is root
$username = "root";
//password to connect to the db
//this is the value you would have specified during installation of WAMP stack
$password = "";
//name of the db under which the table is created
$dbName = "prenajom_sportovisk";
//establishing the connection to the db.
$conn = new mysqli($servername, $username, $password, $dbName);
//checking if there were any error during the last connection attempt
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//the SQL query to be executed
$query = "SELECT SUM(cena) as price, YEAR(DATUM) as rok FROM sportoviska_zakaznici where ID= "; //I need to retrieve that id variable here
//storing the result of the executed query
$result = $conn->query($query);
//initialize the array to store the processed data
$jsonArray = array();
//check if there is any data returned by the SQL Query
if ($result->num_rows > 0) {
//Converting the results into an associative array
while($row = $result->fetch_assoc()) {
$jsonArrayItem = array();
$jsonArrayItem['label'] = $row['rok'];
$jsonArrayItem['value'] = $row['price'];
//append the above created object into the main array.
array_push($jsonArray, $jsonArrayItem);
}
}
//Closing the connection to DB
$conn->close();
//set the response content type as JSON
header('Content-type: application/json');
//output the return value of json encode using the echo function.
echo json_encode($jsonArray);
?>
Is it somehow possible to get this done? I will be really thankful for all suggestions.
In your view pass ID_person and then Use $_GET['ID_person'] in chart_vypozicky.php page
<script type="text/javascript">
$(function() {
$.ajax({
url: "http://localhost/skolaa/chart_vypozicky.php",
type: "GET",
data:{ID_person:'<?php echo $ID_person; ?>'},
success: function(data) {
chartData = data;
var chartProperties = {
caption: "Celková suma za prenájmy počas jednotlivých rokov",
xAxisName: "Rok",
yAxisName: "Suma ",
rotatevalues: "0",
useDataPlotColorForLabels: "1",
theme: "fusion"
};
apiChart = new FusionCharts({
type: "column2d",
renderAt: "chart-container",
width: "550",
height: "350",
dataFormat: "json",
dataSource: {
chart: chartProperties,
data: chartData
}
});
apiChart.render();
}
});
});
</script>
<?php
//address of the server where db is installed
$servername = "localhost";
//username to connect to the db
//the default value is root
$username = "root";
//password to connect to the db
//this is the value you would have specified during installation of WAMP stack
$password = "";
//name of the db under which the table is created
$dbName = "prenajom_sportovisk";
//establishing the connection to the db.
$conn = new mysqli($servername, $username, $password, $dbName);
//checking if there were any error during the last connection attempt
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//the SQL query to be executed
$person_ID=$_GET['ID_person']
$query = "SELECT SUM(cena) as price, YEAR(DATUM) as rok FROM sportoviska_zakaznici where ID='".$person_ID."'"; //I need to retrieve that id variable here
//storing the result of the executed query
$result = $conn->query($query);
//initialize the array to store the processed data
$jsonArray = array();
//check if there is any data returned by the SQL Query
if ($result->num_rows > 0) {
//Converting the results into an associative array
while($row = $result->fetch_assoc()) {
$jsonArrayItem = array();
$jsonArrayItem['label'] = $row['rok'];
$jsonArrayItem['value'] = $row['price'];
//append the above created object into the main array.
array_push($jsonArray, $jsonArrayItem);
}
}
//Closing the connection to DB
$conn->close();
//set the response content type as JSON
header('Content-type: application/json');
//output the return value of json encode using the echo function.
echo json_encode($jsonArray);
?>
Use this updated code

Draw Line Chart (chart data is coming from mysql) based upon selected date from datepicker (Date is coming from mysql table)

What i have trying to do draw a line chart based on date and Id mentioned in the date picker like this
Below is My Code which i am currently using to populate the line chart
HTML CODE (TO show the chart )
<html>
<head>
<title>Temperature chart</title>
</head>
<body>
<div id="chart-container">
<canvas id="mycanvas"></canvas>
</div>
<script type="text/javascript" src="js/jquery-3.4.0.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
data.php (using this file to get the data from mysql and printing it using json)
<?php
//setting header to json
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: http://localhost:8080/hurry/data.php', false);
//database
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'canvasjs_db');
//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query = sprintf("SELECT `temp`, `formatedate` FROM `datapoints` WHERE `device_id` = '50' AND `formatedate` >= '2019-04-02 09:26:00' AND `formatedate` <= '2019-04-03 13:26:00'");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data);
?>
app.js (using this file to populate the data in chart)
$(document).ready(function(){
$.ajax({
url: "http://localhost:8080/Notifications/NewNotification/data.php",
method: "GET",
success: function(data) {
console.log(data);
var player = [];
var score = [];
for(var i in data) {
player.push(data[i].formatedate);
score.push(data[i].temp);
}
var chartdata = {
labels: player,
datasets : [
{
label: 'Temperature ',
hoverBackgroundColor: 'rgba(30, 0, 200)',
hoverBorderColor: 'rgba(200, 200, 197)',
data: score
}
]
};
var ctx = $("#mycanvas");
var lineGraph = new Chart(ctx, {
type: 'line',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});

Parsing JSON array into Google Charts DataTable

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.

Php reference function not found

I am currently working in showing charts using php, html. I have been using a library fusionCharts.php which has been proved working before. However, right now, I have been getting error from the following line >
<?php
class FusionCharts {
private $constructorOptions = [];
private $constructorTemplate = <<<EOD
<script type="text/javascript">
FusionCharts.ready(function () {
new FusionCharts(__constructorOptions__);
});
</script>
EOD;
private $renderTemplate = <<<EOD
<script type='text/javascript'>
FusionCharts.ready(function () {
FusionCharts("__chartId__").render();
});
</script>
EOD;
But firebug shows that my error is being shown from another php funcion, graph.php. I have getting the error from the line 16 which is the line.
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- You need to include the following JS file to render the chart.
When you make your own charts, make sure that the path to this JS file is correct.
Else, you will get JavaScript errors. -->
<script src="js/fusioncharts.js"></script>
</head>
<body>
And the error being thrown:
ReferenceError: FusionCharts is not defined
FusionCharts.ready(function () { graph.php (line 16, col 12)
ReferenceError: FusionCharts is not defined
FusionCharts.ready(function () {
I am adding all the files below:
fusioncharts.js
function fusioncharts_clickbar(){
var chartargs = '';
var chartid = arguments[0];
for (i=0; i<arguments.length; i++) {
chartargs = chartargs + arguments[i] + '/';
}
$.get(Drupal.settings.basePath +"/fusioncharts/data/"+ chartargs ,
function(data){
updateChartXML(chartid, data);
}
);
}
fusioncharts.php
<?php
class FusionCharts {
private $constructorOptions = [];
private $constructorTemplate = <<<EOD
<script type="text/javascript">
FusionCharts.ready(function () {
new FusionCharts(__constructorOptions__);
});
</script>
EOD;
private $renderTemplate = <<<EOD
<script type='text/javascript'>
FusionCharts.ready(function () {
FusionCharts("__chartId__").render();
});
</script>
EOD;
// constructor
function __construct($type, $id, $width = 400, $height = 300, $renderAt, $dataFormat, $dataSource) {
isset($type) ? $this->constructorOptions['type'] = $type : '';
isset($id) ? $this->constructorOptions['id'] = $id : 'php-fc-'.time();
isset($width) ? $this->constructorOptions['width'] = $width : '';
isset($height) ? $this->constructorOptions['height'] = $height : '';
isset($renderAt) ? $this->constructorOptions['renderAt'] = $renderAt : '';
isset($dataFormat) ? $this->constructorOptions['dataFormat'] = $dataFormat : '';
isset($dataSource) ? $this->constructorOptions['dataSource'] = $dataSource : '';
$tempArray = [];
foreach($this->constructorOptions as $key => $value) {
if ($key === 'dataSource') {
$tempArray['dataSource'] = '__dataSource__';
} else {
$tempArray[$key] = $value;
}
}
$jsonEncodedOptions = json_encode($tempArray);
if ($dataFormat === 'json') {
$jsonEncodedOptions = preg_replace('/\"__dataSource__\"/', $this->constructorOptions['dataSource'], $jsonEncodedOptions);
} elseif ($dataFormat === 'xml') {
$jsonEncodedOptions = preg_replace('/\"__dataSource__\"/', '\'__dataSource__\'', $jsonEncodedOptions);
$jsonEncodedOptions = preg_replace('/__dataSource__/', $this->constructorOptions['dataSource'], $jsonEncodedOptions);
} elseif ($dataFormat === 'xmlurl') {
$jsonEncodedOptions = preg_replace('/__dataSource__/', $this->constructorOptions['dataSource'], $jsonEncodedOptions);
} elseif ($dataFormat === 'jsonurl') {
$jsonEncodedOptions = preg_replace('/__dataSource__/', $this->constructorOptions['dataSource'], $jsonEncodedOptions);
}
$newChartHTML = preg_replace('/__constructorOptions__/', $jsonEncodedOptions, $this->constructorTemplate);
echo $newChartHTML;
}
// render the chart created
// It prints a script and calls the FusionCharts javascript render method of created chart
function render() {
$renderHTML = preg_replace('/__chartId__/', $this->constructorOptions['id'], $this->renderTemplate);
echo $renderHTML;
}
}
?>
graph.php
<?php
require ("fusioncharts.php");
error_reporting(E_ERROR);
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
$con=mysql_connect("localhost","root", "");
mysql_select_db("oligolilatest",$con);
?>
<html>
<head>
<title>Comparison of data with other</title>
<p> fdsfdsfds fsd f dsf sdf ds f</p>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- You need to include the following JS file to render the chart.
When you make your own charts, make sure that the path to this JS file is correct.
Else, you will get JavaScript errors. -->
<script src="js/fusioncharts.js"></script>
</head>
<body>
<?php
$query = "SELECT UserID,FirstName FROM customerregistration ";
$result = mysql_query($query);
//echo "here1";
// If the query returns a valid response, prepare the JSON string
if ($result) {
// The `$arrData` array holds the chart attributes and data
// echo "here11";
$arrData = array(
"chart" => array(
"caption" => "Number of User and Customer in the website",
"paletteColors" => "#0075c2",
"bgColor" => "#ffffff",
"borderAlpha"=> "20",
"canvasBorderAlpha"=> "0",
"usePlotGradientColor"=> "0",
"plotBorderAlpha"=> "10",
"showXAxisLine"=> "1",
"xAxisLineColor" => "#999999",
"showValues" => "0",
"divlineColor" => "#999999",
"divLineIsDashed" => "1",
"showAlternateHGridColor" => "0"
)
);
$arrData["data"] = array();
// Push the data into the array
while($row = mysql_fetch_assoc($result)) {
array_push($arrData["data"], array(
"label" => $row["FirstName"],
"value" => $row["UserID"],
)
);
}
/*JSON Encode the data to retrieve the string containing the JSON representation of the data in the array. */
// echo "here3";
$jsonEncodedData = json_encode($arrData);
echo $jsonEncodedData;
/*Create an object for the column chart using the FusionCharts PHP class constructor. Syntax for the constructor is ` FusionCharts("type of chart", "unique chart id", width of the chart, height of the chart, "div id to render the chart", "data format", "data source")`. Because we are using JSON data to render the chart, the data format will be `json`. The variable `$jsonEncodeData` holds all the JSON data for the chart, and will be passed as the value for the data source parameter of the constructor.*/
$columnChart = new FusionCharts("column2D", "myFirstChart" , 600, 300, "chart-1", "json", $jsonEncodedData);
// Render the chart
$columnChart->render();
}
?>
<div id="chart-1"><!-- Fusion Charts will render here-->
</div> </body></html>
Thank you.
Well you have given us quite some code to plow through; and it seems the fusioncharts.js you include in your <HEAD> (which you have also included in your post) simply doesn't include the FusionCharts class so there must be additional javascript files you need to include. Looking at their documentation you also need to include the library like this:
<script type="text/javascript" src="FusionCharts/FusionCharts.js"></script>
Don't you include this library already in your other, working pages?

Categories