PHP, geojson and openlayers - php

I stuck completely going through scripting with openlayers. I have database in postgis with coordinates and height values and even geometry column for each row. I create form with submit button to retrieve data only according to entered value by the user. When I press the submit button the PHP is getting correct data and transform into JSON format which I have displayed as result. Somebody know how to load these results into openlayers layer and display those points?
Thats the main page:
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome to my maps</title>
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
<script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script>
<link rel="stylesheet" href="http://openlayers.org/api/theme/default/style.css" type="text/css" />
<style type="text/css">
#bmap {
width:83%;
height:90%;
border:2px solid black;
position:absolute;
top:10px;
left:200px;
}
body{
background:yellow;
}
</style>
<script>
var mapoptions = {
theme: null,
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
maxResolution: 156543.0399,
numZoomLevels: 20,
units: 'm',
projection: new OpenLayers.Projection("EPSG:900913"),
displayProjection: new OpenLayers.Projection("EPSG:4326"),
controls:[
new OpenLayers.Control.PanZoomBar(),
new OpenLayers.Control.Navigation(),
new OpenLayers.Control.LayerSwitcher(),
new OpenLayers.Control.MousePosition(),
new OpenLayers.Control.ScaleLine(),
new OpenLayers.Control.Scale()
]
};
function init() {
map = new OpenLayers.Map("bmap", mapoptions);
var mapnik = new OpenLayers.Layer.OSM("OSM Mapnik");
map.addLayer(mapnik);
var cyclemap = new OpenLayers.Layer.OSM("OSM CycleMap");
map.addLayer(cyclemap);
var wmslayer = new OpenLayers.Layer.WMS(
"Altitude points",
"http://192.168.56.101:8080/geoserver/wms",
{'layers': 'dublin_flooding:dublin', 'format':'image/png', 'transparent':'true'},
{'opacity': 1.0, 'isBaseLayer': false, 'visibility': false}
);
map.addLayer(wmslayer);
var veclayer=new OpenLayers.Layer.Vector("geojson",{
strategies: [new OpenLayers.Strategy.Fixed()],
protocol: new OpenLayers.Protocol.HTTP({
url: "query5.php",
format: new OpenLayers.Format.GeoJSON(),
internalProjection: new OpenLayers.Projection("EPSG:900913"),
externalProjection: new OpenLayers.Projection("EPSG:4326")
}),
});
map.addLayer(veclayer);
map.setCenter(new OpenLayers.LonLat(-6.26555,53.34590) // Center of the map
.transform(
new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
), 12 // Zoom level
);
}
</script>
</head>
<body>
<h3>Flooding projection</h3>
<form action="query5.php" method="POST" name="form">
<table cellpadding="0">
<tr>
<td>
<p>Meters:</p>
</td>
<td>
<input name="sliderValue" id="sliderValue" type="Text" size="3">
</td>
</tr>
<tr>
<td>
<input name="Submit" type="Submit" value="Submit">
</td>
</tr>
</table>
</form>
<body onload="init();">
<div id="bmap"></div>
</body>
</html>
`
And PHP query is looks like that:
`<?php
$db = pg_connect("host=localhost port=5432 dbname=firstSpatialDB user=postgres password=postgres");
$query = "SELECT* FROM dublin where alt<='$_POST[sliderValue]'";
$result = pg_query($query);
// Return route as GeoJSON
$geojson = array(
'type' => 'FeatureCollection',
'features' => array()
);
// Add edges to GeoJSON array
while($row=pg_fetch_array($result)) {
$feature = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
'coordinates' => array($row[1], $row[2])
),
'properties' => array(
'gid' => $row[0],
'alt' => $row[3]
)
);
// Add feature array to feature collection array
array_push($geojson['features'], $feature);
}
pg_close($dbconn);
// Return routing result
header("Content-Type:application/json",true);
//header("Location:map.html");
echo json_encode($geojson);
?> `
In my view that should be working, but is not at all.
Maybe somebody has idea what is wrong. Thanks for any suggestions, as I really have enough my own.

I have never used php, so I don't know if that's where your problem is.
Compare your code to this, it worked for me, maybe your error is in the javascript.
var map;
function init(){
map = new OpenLayers.Map('map');
var options = {numZoomLevels: 3}
var floorplan = new OpenLayers.Layer.Image(
'Floorplan Map',
'../../temp_photos/sample-floor-plan.jpg',
new OpenLayers.Bounds(-300, -188.759, 300, 188.759),
new OpenLayers.Size(580, 288),
options
);
map.addLayer(floorplan);
//Create a Format object
var vector_format = new OpenLayers.Format.GeoJSON({});
//Create a Protocol object using the format object just created
var vector_protocol = new OpenLayers.Protocol.HTTP({
url: 'ex5_data.json',
format: vector_format
});
//Create an array of strategy objects
var vector_strategies = [new OpenLayers.Strategy.Fixed()];
//Create a vector layer that contains a Format, Protocol, and Strategy class
var vector_layer = new OpenLayers.Layer.Vector('More Advanced Vector Layer',{
protocol: vector_protocol,
strategies: vector_strategies
});
map.addLayer(vector_layer);
if(!map.getCenter()){
map.zoomToMaxExtent();
}
}

I just tried your code (chri_chri) .
I tried to load an images but seem to be wrong...
Im also now to openlayers
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Floorplan test</title>
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
<script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script>
<link rel="stylesheet" href="http://openlayers.org/api/theme/default/style.css" type="text/css" />
<style type="text/css">
#bmap {
width:83%;
height:90%;
border:2px solid black;
position:absolute;
top:10px;
left:200px;
}
body{
background:yellow;
}
</style>
<script>
var map;
function init(){
map = new OpenLayers.Map('map');
var options = {numZoomLevels: 3}
var floorplan = new OpenLayers.Layer.Image(
'Floorplan Map',
'png_1.jpg',
new OpenLayers.Bounds(-300, -188.759, 300, 188.759),
new OpenLayers.Size(580, 288),
options
);
map.addLayer(floorplan);
//Create a Format object
var vector_format = new OpenLayers.Format.GeoJSON({});
//Create a Protocol object using the format object just created
var vector_protocol = new OpenLayers.Protocol.HTTP({
url: 'ex5_data.json',
format: vector_format
});
//Create an array of strategy objects
var vector_strategies = [new OpenLayers.Strategy.Fixed()];
//Create a vector layer that contains a Format, Protocol, and Strategy class
var vector_layer = new OpenLayers.Layer.Vector('More Advanced Vector Layer',{
protocol: vector_protocol,
strategies: vector_strategies
});
map.addLayer(vector_layer);
if(!map.getCenter()){
map.zoomToMaxExtent();
}
}
</script>
</head>
<body>
<h3>Floorplan</h3>
<body onload="init();">
<div id="bmap"></div>
</body>
</html>
What im starting up with is to load a floorplan map and try to scale it.

you can look at this example postgis to geojson php clarifying how to use a php script the get geojson data through postgis database.
and as you did in your geojson layer url, u pass the url of your php script...
hope it helps;

I use PostGis together with Openlayers 3/4 without GeoServer. The way I choose is to get geojson from a Postgis-database via a function I call, which returns the data and styles it acording to my settings.
In Javascript I define the data and styling => Javascript-function calls a php-script via GET to retrive data from Postgis => function styles the data to render in Openlayers 3. The whole sripts can be seen in Is there an easy way to use Postgis-geojson in Openlayers 3?
Be aware, that the proposed solution is not secure, because GET-strings could be manipulated (sql-injections). I use a call via https and the serverside php-script checks if a SESSION is set. So the scripts cannot be executed without beeing logged in. We use this in a very small group, but it might be not a good idea to use it in an environment, where many poeple are accessing the data.
So improvments in security would be good.

You can use PHP
<?php
ini_set('display_errors', 1);
# Connect to PostgreSQL database
$conn = pg_connect("dbname='gisdata' user='username'
password='password' host='localhost'")
or die ("Could not connect to server\n");
$result = pg_fetch_all(pg_query($conn, "SELECT row_to_json(fc)
FROM ( SELECT 'FeatureCollection' As type,
array_to_json(array_agg(f)) As features
FROM (SELECT 'Feature' As type
, ST_AsGeoJSON(lg.geom, 4)::json As geometry
, row_to_json((SELECT l FROM (SELECT id, designacao) As l
)) As properties
FROM hidrog As lg ) As f ) As fc;"));
if (!$result) {
echo "An error occurred.\n";
exit;
}
#echo json_encode($result, JSON_NUMERIC_CHECK);
$json_data = json_encode($result);
file_put_contents('test.json', $json_data);
$jsonString = file_get_contents('test.json');
$json_new = substr($jsonString, 17,-2);
$json_new = str_ireplace('\"', '"', $json_new);
echo $json_new;
file_put_contents('test_new.json', $json_new);
?>

Related

Google.visualization.dashboard not rendering with json array php

I’m passing an encoded json array from a MYSQL query to render a google.visualization.dashboard. I am almost certain the problem is with my array but I can't find where. The code works when I draw the chart google charts directly (eg google.visualization.PieChart) but not when I use dashboard / control wrapper / chart wrapper classes.
That leads me to believe that the problem is either with my array structure or that google.visualization.dashboard requires the data table to be populated differently than the charts.
PHP code (loadpiechart.php):
$table['cols'] = array(
array('label' => 'NZ Crime', 'type' => 'string'),
array('label' => 'Value', 'type' => 'number'),
);
$rows=array();
while($r=mysqli_fetch_assoc($res)){
$temp=array();
$temp[]=array('v'=> $r['Offence']);
$temp[]=array('v' => $r['Total']);
$rows[]=array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table, JSON_NUMERIC_CHECK);
echo $jsonTable;
Which gives me the following array[]
{"cols":[{"id":"A","label":"NZ Crime","type":"string"},{"id":"B","label":"Value","type":"number"}],"rows":[{"c":[{"v":" Acts intended to cause injury"},{"v":97}]},{"c":[{"v":" Sexual assault and related offences"},{"v":44515}]},{"c":[{"v":" Dangerous or negligent acts endangering persons"},{"v":3016}]},{"c":[{"v":" Abduction, harassment and other related offences against a person"},{"v":859}]},{"c":[{"v":" Robbery, extortion and related offences"},{"v":14157}]},{"c":[{"v":" Unlawful entry with intent\/burglary, break and enter"},{"v":2641}]},{"c":[{"v":" Theft and related offences"},{"v":59323}]},{"c":[{"v":" Fraud, deception and related offences"},{"v":136932}]},{"c":[{"v":" Illicit drug offences"},{"v":9726}]},{"c":[{"v":" Prohibited and regulated weapons and explosives offences"},{"v":22994}]},{"c":[{"v":" Property damage and environmental pollution"},{"v":7074}]},{"c":[{"v":" Public order offences"},{"v":58483}]},{"c":[{"v":" Offences against justice procedures, government security and government operations"},{"v":46105}]},{"c":[{"v":" Miscellaneous offences"},{"v":19084}]}]}
And finally the HTML code.
html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.charts.load('current', {packages:['corechart', 'table', 'controls']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawTable);
function drawTable() {
var jsonData = $.ajax({
url: "loadpiechart.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 table = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'table_div',
});
var chart = new google.visualization.ChartWrapper({
'chartType': 'PieChart',
'containerId': 'chart_div',
'view': {'columns': [0, 1]},
});
var control = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'control_div',
'options': {
'filterColumnIndex': 0,
}
});
var dashboard = new google.visualization.Dashboard(
document.getElementById('dashboard_div'));
dashboard.bind([control], [table,chart]);
dashboard.draw(data);
}
</script>
</head>
<body>
<div id="dashboard_div" style="border: 1px solid #ccc; margin-top: 1em">
<p style="padding-left: 1em"><strong>NZ Crime Stats</strong></p>
<table class="columns">
<tr>
<td>
<div id="control_div" style="padding-left: 15px"></div>
</td>
</tr><tr>
<td>
<div id="chart_div" style="padding-top: 15px"></div>
</td><td>
<div id="table_div" style="padding-top: 30px"></div>
</td>
</tr>
</table>
</div>
</body>
</html>
I would recommend to change the AJAX call to a non-blocking asynchronous call and call the drawing routine in the success() method:
function drawTable() {
$.ajax("https://gist.githubusercontent.com/Moonbird-IT/da4c7d76a69eb250478bb55b5d2360f5/raw/9dbf9d92981a3c9b71906dd3a680a2cdeca7c4aa/googlecharts.json", {
dataType: "json",
success: function(jsonData) {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
...
}
});
}
I updated your code to use the changed recommendation, here is a working Fiddle of it.
My problem was that I wasn't calling jQuery. I added this line of code and it works my original code plus this addition.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Link here for google.visaulization documentation https://developers.google.com/chart/interactive/docs/php_example

Changing the legend/labels in Google Chart

I am pulling data from a database via mysqli to create a Google pie Chart. The data is from one column (a1), but each entry is different (eg, a, b, c) and I am listing the percentage of responses for each entry/answer.
So for instance,
a = 20%
b = 30%
Each entry corresponds to a different social media type, which I need to show but is not shown in the database itself. Is there a way to change the legend of the chart so that instead of listing A, B, C it would replace that with a custom label? (Eg, instead of showing 'A' show 'Facebook').
my column
my current chart
I have tried using title under var data, label under options, legend under options. I feel like I'm missing something
<?php
$connect = mysqli_connect("localhost", "root", "root", "survey");
$query = "SELECT a1, count(*) as number FROM rtp2k GROUP BY a1";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Sad me is Sad </title>
<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([
['social', 'number'],
<?php
while($row = mysqli_fetch_array($result))
{
echo "['".$row["a1"]."', ".$row["number"]."],";
}
?>
]);
var options = {
title: 'Which social networks do you use most often?',
//is3D:true,
pieHole: 0.4,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<br /><br />
<div style="width:900px;">
<h3 align="center">Make Simple Pie Chart by Google Chart API with PHP Mysql</h3>
<br />
<div id="piechart" style="width: 900px; height: 500px;">
</div>
</div>
</body>
</html>
Right now my legend lists the type by what is in the database, (eg, a, b, c) I would like to replace the letters with my own label/title (eg, instead of 'a', I would like it to say 'Facebook'.
Edited for consistency.
we can use a DataView with a calculated column,
to convert the values the network names.
first, create an object to map the values to the names.
var socialNetworks = {
a: 'Facebook',
b: 'Instagram',
c: 'LinkedIn'
};
then we create a DataView from the DataTable.
var view = new google.visualization.DataView(data);
then use method setColumns to add a calculated column for the conversion.
we use the column index of the number, since it won't be changing.
view.setColumns([{
calc: function (dt, row) {
return socialNetworks[data.getValue(row, 0)];
},
label: 'social',
type: 'string'
}, 1]);
then use the DataView to draw the chart.
chart.draw(view, options);
full snippet...
var data = google.visualization.arrayToDataTable([
['social', 'number'],
<?php
while($row = mysqli_fetch_array($result))
{
echo "['".$row["a1"]."', ".$row["number"]."],";
}
?>
]);
var options = {
title: 'Which social networks do you use most often?',
//is3D:true,
pieHole: 0.4,
};
var socialNetworks = {
a: 'Facebook',
b: 'Instagram',
c: 'LinkedIn'
};
var view = new google.visualization.DataView(data);
view.setColumns([{
calc: function (dt, row) {
return socialNetworks[data.getValue(row, 0)];
},
label: 'social',
type: 'string'
}, 1]);
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(view, options);

PHP array into google charts

I need a little help putting PHP data into google charts.
I have created a simple array
$chart_arr = array($year, $new_balance);
json_encode($chart_arr);
If I run
<?php echo json_encode($chart_arr);?>
I see the following: [2015,1150] [2016,1304.5] [2017,1463.635] [2018,1627.54405] [2019,1796.3703715], so I think (?) I am getting the right numbers encoded from my forloop that generates $year and $new_balance.
I want to chart these numbers in google chart
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Year');
data.addColumn('number', 'Balance');
data.addRows([
<?php echo json_encode($chart_arr);?>
]);
Or alternatively:
data.addRows([
<?php echo $chart_arr;?>
]);
And then continues...
var options = {
title: 'My Savings',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
displaying as...
<div class="grid-container">
<div class="grid-100 grid-parent">
<div id="curve_chart" style="width: 100%; height: auto"></div>
</div>
</div>
I have tried a number of variations but am either not getting the data into the chart or not getting a chart to display.
Could someone help me to show where I am going wrong?
I saw another related post that used the following code:
$chartsdata[$i] = array($testTime, $testNb);
echo json_encode($chartsdata);
var jsonData = $.ajax({
url: "test.php",
dataType: "json",
async: false
}).responseText;
var obj = JSON.stringify(jsonData);
data.addRows(obj);
Is this the approach I need to be looking at?
Thanks in advance
i see you haven't found out how to do it after your first question, so i've made you a working example here, hope this helps you Dave :).
If you've got some questions about this, feel free to ask!
<?php
//create array variable
$values = [];
//pushing some variables to the array so we can output something in this example.
array_push($values, array("year" => "2013", "newbalance" => "50"));
array_push($values, array("year" => "2014", "newbalance" => "90"));
array_push($values, array("year" => "2015", "newbalance" => "120"));
//counting the length of the array
$countArrayLength = count($values);
?>
<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 data = new google.visualization.DataTable();
data.addColumn('string', 'Year');
data.addColumn('number', 'Balance');
data.addRows([
<?php
for($i=0;$i<$countArrayLength;$i++){
echo "['" . $values[$i]['year'] . "'," . $values[$i]['newbalance'] . "],";
}
?>
]);
var options = {
title: 'My Savings',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
<div class="grid-container">
<div class="grid-100 grid-parent">
<div id="curve_chart" style="width: 100%; height: auto"></div>
</div>
</div>
I have dealt quite a bit with the Google Charts API recently and I have a few recommendations. The PHP code that you have written should largely work, but it does require that your Javascript code be embedded in a PHP page.
Maybe that is okay for your purposes, but I mostly recommend keeping your Javascript separate from your PHP. Some developers may be comfortable with one, but not the other, so mixing the two languages could become a maintenance issue. Now, that pretty much leaves you with using AJAX to retrieve your JSON charts data. This is a good approach, but I do not like the code that you featured in your question for a few reasons.
Firstly, the code uses async: false which will remove your user's control of the browser while the data is being fetched. In other words, the browser will appear to freeze until the data is returned from the AJAX request.
Also, I do not understand the whole .responseText convention. I understand what the code is accomplishing; I just fail to understand why the author chose that particular approach. Here is what I would do instead.
$.ajax({
url: "test.php",
dataType: "JSON",
data: [any POST parameters that you need here],
type: "POST",
success: function(json) {
var jsonData = JSON.parse(json); // jsonData will be a Javascript object or array.
data.addRows(jsonData);
drawChart();
},
error: function(jxqhr) {
// Handle a bad AJAX call
}
});
So how does this help your application overall? Well, in your server side code, you can handle any errors (i.e. bad user input) by responding to the AJAX call with a HTTP 500 error and the AJAX call can communicate the problem to your user. Furthermore, when your page loads, the rest of the page will continue loading while your AJAX call is off fetching data.
JS Fiddle
json_encode works just fine, you can put it in a variable like var grafica = <?php echo json_encode($grafica); ?> ; (look my example below) or just like you put it in your example, except that the only problem in it, is that you have double brackets, the ones inside jaso_encode($chart_arr) object and the externals data.addRows([ ... ]), that gives you [[...]] and generates and error, take off the brackets, try it like this:
data.addRows(
<?php echo json_encode($chart_arr);?>
);
and not this
data.addRows([
<?php echo json_encode($chart_arr);?>
]);
I have included and example of how I am using it, be aware that in the documentation, (which in my opinion could be better) they placed the entire code in the <head> section because they have all the data there, but that may cause problems in real working examples, I only placed the CDN (Content Delivery Network) of google chart in the <head> and in the <body> all the Javascript code after the PHP code, not included in this example for clarity purposes, then the <div> but this last could go before the script tags. The order is important because you need to get the data first before constructing the graph.
I hope this helps.
<!DOCTYPE html>
<head>
<meta charset="utf-8"/>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'fecha'); // Implicit domain column.
data.addColumn('number', 'peso'); // Implicit data column.
data.addColumn({type:'string', role:'annotation'}); // columna para anotaciones
data.addColumn({type:'string', role:'style'}); // comumna para estilo
var grafica = <?php echo json_encode($grafica); ?> ;
data.addRows(grafica);
var options = {
title:'Peso Total', width:600,height:400,
colors: ['#C0C0C0'],
curveType: 'function',
legend: 'none',
pointSize: 12,
annotations: {
textStyle: {
fontName: 'Times-Roman',
fontSize: 32,
color: '#99ff99',
opacity: 0.5,
}
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div" style="margin: 80px auto; width: 650px; height: 450px; border: 2px solid #4CAF50; border-radius: 20px; padding:5px; "></div>
</html>

unable to display Google Chart with json table

I'm fairly new to the coding world so please have mercy regarding my obsolete SQL connection although the wpdp class does exist. I am aware of this, but for some reasons, it doesn't work and that's another topic...
I try to write my own plugin to connect to my sql database, query some stuff and then provide a google chart with a jsontable. The code works If I use it in a stand alone .php file. However, as soon as I activate do_action nothing works and my whole page is white.
<?php
/*
Plugin Name: mm_gchart
Description: -
Version: 1.0.0
Author: MM
*/
function mm_gct_data() {
$con=mysqli_connect("localhost","xx","xx","xx");
// Check connection
if (mysqli_connect_errno()) {
//echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//echo "Hello";
$sql="SELECT gewicht, wdh FROM testtable";
$query=mysqli_query($con, $sql);
$rows=array();
$table=array();
$table['cols'] = array(
array('label' => 'Gewicht', 'type' => 'number'),
array('label' => 'Wiederholungen', 'type' => 'number')
);
while ($r = mysqli_fetch_assoc($query))
{
$temp=array();
$temp[]=array('v' => (int) $r['gewicht']);
$temp[]=array('v' => (int) $r['wdh']);
$rows[]=array('c' => $temp);
}
global $jsonTable;
$table['rows'] = $rows;
$jsonTable = json_encode($table);
}
add_action('init', 'mm_gct_data');
//do_action( 'init','mm_gct_data' );
?>
I would be super happy, if somebody could work some black magic on my code and then provide a simple description.
Thanks in advance!
Edit after replies:
Thank you very much for your fast reply! If the do_action() command was not the reason for my blank page, then what is?
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.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() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var options = {
title: 'Testing',
width: 600,
height: 400
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
<p>Everything went well..</p>
</body>
</html>
You should not make a call to do_action() as you have it in your code. This action hook is built into WordPress and will be called automatically as part of its running. The WordPress site has a list of the Actions Run During a Typical Request on their site.
It is appropriate to make a call to do_action() when you want to implement a custom action hook for other developers to plug in to. Calls to add_action() can be made to add events to your hook.

Display a google chart with json & PHP

I'm trying to generate a google chart from mysql data using php.
Here is my code so far :
get_json.php
<?php
/* $server = the IP address or network name of the server
* $userName = the user to log into the database with
* $password = the database account password
* $databaseName = the name of the database to pull data from
* table structure - colum1 is cas: has text/description - column2 is data has the value
*/
$con = mysql_connect('localhost','root','') ;
mysql_select_db('gcm', $con);
// write your SQL query here (you may use parameters from $_GET or $_POST if you need them)
$query = mysql_query('SELECT count(name) As Subscribers,CAST(`created_at` AS DATE) As Date FROM gcm_users GROUP BY created_at ORDER BY created_at')or die(mysql_error());
$table = array();
$table['cols'] = array(
/* define your DataTable columns here
* each column gets its own array
* syntax of the arrays is:
* label => column label
* type => data type of column (string, number, date, datetime, boolean)
*/
// I assumed your first column is a "string" type
// and your second column is a "number" type
// but you can change them if they are not
array('label' => 'Date', 'type' => 'string'),
array('label' => 'Subscribers', 'type' => 'number')
);
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$temp = array();
// each column needs to have data inserted via the $temp array
$temp[] = array('v' => $r['Date']);
$temp[] = array('v' => (int) $r['Subscribers']);
// insert the temp array into $rows
$rows[] = array('c' => $temp);
}
// populate the table with rows of data
$table['rows'] = $rows;
// encode the table as JSON
$jsonTable = json_encode($table);
// set up header; first two prevent IE from caching queries
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
// return the JSON data
echo $jsonTable;
?>
It displays right : {"cols":[{"label":"Date","type":"string"},{"label":"Subscribers","type":"number"}],"rows":[{"c":[{"v":"2013-04-14"},{"v":1}]},{"c":[{"v":"2013-04-15"},{"v":1}]}]}
This is where I display :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>
Google Visualization API Sample
</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart']});
</script>
<script type="text/javascript">
function drawVisualization() {
var jsonData = null;
var json = $.ajax({
url: "get_json.php", // make this url point to the data file
dataType: "json",
async: false,
success: (
function(data) {
jsonData = data;
})
}).responseText;
// Create and populate the data table.
var data = new google.visualization.DataTable(jsonData);
// Create and draw the visualization.
var chart= new google.visualization.LineChart(document.getElementById('visualization')).
draw(data, {curveType: "function",
width: 500, height: 400,
vAxis: {maxValue: 10}}
);
}
google.setOnLoadCallback(drawVisualization);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="visualization" style="width: 500px; height: 400px;"></div>
</body>
</html>
But when i run this code I got nothing,it's blank ! Where is my error?
Now tested:
You haven't included jQuery in your page. Add this line in your <head> and it works.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Another thing that can happen if your AJAX call takes a little longer:
By the time your success: function() is called after the AJAX call is finished the rest of the script has already run. The script doesn't wait until the AJAX call is finished until the "Create and populate" part is executed. You have to place these lines inside the success: function().
<script type="text/javascript">
function drawVisualization() {
var jsonData = null;
var json = $.ajax({
url: "get_json.php", // make this url point to the data file
dataType: "json",
async: false,
success: (
function(data) {
jsonData = data;
// Create and populate the data table.
var data = new google.visualization.DataTable(jsonData);
// Create and draw the visualization.
var chart= new google.visualization.LineChart(document.getElementById('visualization')).
draw(data, {curveType: "function",
width: 500, height: 400,
vAxis: {maxValue: 10}}
);
})
}).responseText;
}
google.setOnLoadCallback(drawVisualization);
</script>
This way you can make sure that all relevant code is only executed after the AJAX call has finished.

Categories