Google Geo Chart - php

I'm using Google's Geo Charts API, and using json to update the data.
This is my map js (map.php):
google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var jsonData = $.ajax({
url: "includes/_ajax_home_map.php?metric=Clicks",
dataType:"json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
var options = {
//region: '009',
backgroundColor: 'EAF7FE',
colorAxis: {colors: ['910101']}
};
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data, options);
};
This is my php generated json (_ajax_home_map.php):
$data = '{
"cols": [
{"id":"","label":"Country","pattern":"","type":"string"},
{"id":"","label":"Popularity","pattern":"","type":"number"}
],
"rows": [';
$metric = $_REQUEST['roi_tag'];
$sql = "SELECT SUM($metric) as '$metric',tag_1 FROM Dashboard_ClientsCampaigns_Today_HoH WHERE tag_1 != '' GROUP BY tag_1";
$sql = mysql_query($sql);
$count = 1;
while($row = mysql_fetch_array($sql)){
$tag_1 = strtoupper($row["tag_1"]);
if($tag_1 == "UK")$tag_1 = "GB";
if($count != 1)$data .= ",";
$count++;
$data .= '{"c":[{"v":"'.$tag_1.'","f":null},{"v":'.$row[$metric].',"f":null}]}';
}
$data .= ']}';
echo $data;
Now when I connect these 2, I just get a blank map. No data is in there. BUT..here comes the strange part. If I browse directly to my PHP JSON, I get this:
{ "cols": [ {"id":"","label":"Country","pattern":"","type":"string"}, {"id":"","label":"Popularity","pattern":"","type":"number"} ], "rows": [{"c":[{"v":"AU","f":null},{"v":139,"f":null}]},{"c":[{"v":"CZ","f":null},{"v":3,"f":null}]},{"c":[{"v":"DE","f":null},{"v":4,"f":null}]},{"c":[{"v":"DK","f":null},{"v":978,"f":null}]},{"c":[{"v":"ES","f":null},{"v":32,"f":null}]},{"c":[{"v":"HU","f":null},{"v":2,"f":null}]},{"c":[{"v":"IE","f":null},{"v":65,"f":null}]},{"c":[{"v":"IT","f":null},{"v":5081,"f":null}]},{"c":[{"v":"PT","f":null},{"v":4452,"f":null}]},{"c":[{"v":"RO","f":null},{"v":16,"f":null}]},{"c":[{"v":"RS","f":null},{"v":0,"f":null}]},{"c":[{"v":"RU","f":null},{"v":0,"f":null}]},{"c":[{"v":"SE","f":null},{"v":69,"f":null}]},{"c":[{"v":"GB","f":null},{"v":28123,"f":null}]}]}
If I take this outputted JSON, copy it, home it in it's own file (data2.php), then get my map js to access it, it populates the map perfectly.
How on earth can I have 2 pieces of identical JSON and only one work with Google Charts?

Maybe because you try to load the PHP with the wrong param
_ajax_home_map.php?metric=Clicks
but in the code you look for
$metric = $_REQUEST['roi_tag'];
try
$metric = $_REQUEST['metric'];
..instead. And you are right by the way - the JSON works just fine! Thats not the problem.

Related

Google visualization world map

I'm trying to retrieve results using json in order to display world map with country list.
This is what I got so far:
function drawRegionsMap() {
$.ajax({
url: 'getlist.php",
dataType: "json"
}).done(function(result) {
var data = google.visualization.arrayToDataTable(result);
var view = new google.visualization.DataView(data)
view.setColumns([0, 1])
var chart = new google.visualization.GeoChart(
document.getElementById('map'));
chart.draw(data, options);
var geochart = new google.visualization.GeoChart(
document.getElementById('map'));
var options = {
width: "auto",
height: "auto",
colorAxis: {
colors: ['#E4B6D3', '#E06D94']
} // Map Colors
};
geochart.draw(data, options);
});
};
google.load('visualization', '1', {
'packages': ['geochart']
});
google.setOnLoadCallback(drawRegionsMap);
result returned from getlist.php is in json format:
{
"Country":[
"Germany",
"United States",
"Brazil",
"France",
"RU"
],
"Hits":[
200,
300,
400,
500,
600,
700
]
}
php code:
$data = array();
$data['Country'] = array();
$data['Hits'] = array();
$country = array('Germany','United States','Brazil','France','RU');
$hits = array(200,300,400,500,600,700);
for ($i = 0; $i < 6; $i++){
$data['Country'] = $country;
$data['Hits'] = $hits;
}
echo json_encode($data);
Looking in firebug console, I'm always getting : Error: Not an array
I've been trying to solve this puzzle for hours, but no success.
The returned result is an object, not an array.
The expected array would be:
[
["Country","Hits"],
["Germany",200],
["United States",300],
["Brazil",400],
["France",500],
["RU",600]
]
Modified PHP-code that returns this array:
<?php
$data = array(['Country','Hits']);
$country = array('Germany','United States','Brazil','France','RU');
$hits = array(200,300,400,500,600,700);
foreach ($country as $k => $v){
$data[] = array($v,$hits[$k]);
}
echo json_encode($data);
?>

Google Charts and MYSQL

i am new with PHP and Google charts. What i am trying to do it to make google charts with arduino data storred in a MYSL database. So far i insert data from arduino to mysql DB successfully but i face difficulties with the google charts.
Here is my PHP code:
<?php
$mysqli =mysqli_connect('localhost', 'root', '', 'Arduino');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$sql = mysqli_query($mysqli, 'SELECT * FROM analoog0');
if (!$sql) {
die("Error running $sql: " . mysql_error());
}
$results = array();
while($row = mysqli_fetch_assoc($sql))
{
$results[] = array(
'Date' => $row['Date'],
'Time' => $row['Time'],
'Temperature' => $row['Temperature']
);
}
$json = json_encode($results, JSON_PRETTY_PRINT);
echo $json;
?>
Here is the JSON output:
[ { "Date": "2013-10-24", "Time": "18:15:49", "Temperature": "24" },
{ "Date": "2013-10-24", "Time": "18:16:19", "Temperature": "24" },
{ "Date": "2013-10-24", "Time": "18:16:49", "Temperature": "24" },
{ "Date": "2013-10-24", "Time": "18:17:19", "Temperature": "23" } ]
And finally the HTM code:
<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() {
var jsonData = $.ajax({
url: "localhost/Charts/chart_ver2.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
When i run the HTM code nothing happens - the screen remains blank.
Any help, guidance or redirection will be highly appreciated!
Thanks in advance!!
You need to format the data correctly for the Visualization API. This should put your data in the correct format:
$results = array(
'cols' => array (
array('label' => 'Date', 'type' => 'datetime'),
array('label' => 'Temperature', 'type' => 'number')
},
'rows' => array()
);
while($row = mysqli_fetch_assoc($sql)) {
// date assumes "yyyy-MM-dd" format
$dateArr = explode('-', $row['Date']);
$year = (int) $dateArr[0];
$month = (int) $dateArr[1] - 1; // subtract 1 to make month compatible with javascript months
$day = (int) $dateArr[2];
// time assumes "hh:mm:ss" format
$timeArr = explode(':', $row['Time']);
$hour = (int) $timeArr[0];
$minute = (int) $timeArr[1];
$second = (int) $timeArr[2];
$results['rows'][] = array('c' => array(
array('v' => "Date($year, $month, $day, $hour, $minute, $second)"),
array('v' => $row['Temperature'])
));
}
$json = json_encode($results, JSON_NUMERIC_CHECK);
echo $json;
In your javascript, I would recommend rearranging the way you handle the AJAX query. There's nothing wrong per say with the way you are doing it, but I think this is a more elegant solution:
function drawChart() {
$.ajax({
url: 'localhost/Charts/chart_ver2.php',
dataType: 'json',
success: function (jsonData) {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
});
}
You can't use the .responseText with a JSON response, as far as I know it only works for XML and Text.
$.ajax({
url: "localhost/Charts/chart_ver2.php",
dataType:"json",
async: false
}).responseText;
I would change it to:
$.ajax({
url: "localhost/Charts/chart_ver2.php",
dataType:"json",
async: false ,
success: function(data) {
jsonData = data;
}
});

Passing json to php and updating mysql

I'm trying to pass image coordinates via json to a php file that should update the database.
I have this in jquery:
var coords=[];
var coord = $(this).position();
var item = { coordTop: coord.top, coordLeft: coord.left };
coords.push(item);
var order = { coords: coords };
$.ajax({
type: "POST",
data : +$.toJSON(order),
url: "updatecoords.php",
success: function(response){
$("#respond").html('<div class="success">X and Y Coordinates
Saved</div>').hide().fadeIn(1000);
setTimeout(function(){
$('#respond').fadeOut(1000);
}, 2000);
}
});
This is what updatecoords.php looks like:
<?php
$db = Loader::db();
$data = json_decode($_POST['data']);
foreach($data->coords as $item) {
$coord_X = preg_replace('/[^\d\s]/', '', $item->coordTop);
$coord_Y = preg_replace('/[^\d\s]/', '', $item->coordLeft);
$x_coord = mysql_real_escape_string($coord_X);
$y_coord = mysql_real_escape_string($coord_Y);
$db->Execute("UPDATE coords SET x_pos = '$x_coord', y_pos = '$y_coord'");
}
?>
The success message shows from the javascript however nothing gets updated in the database?
Any thoughts?
You have a + before $.toJSON. Meaning that the json string it returns will be converted to an integer - probably 0 or NaN.
Alex is right, but you can also take the quotes out from the preg_replace pattern. PHP naturally uses /.../ slashes to "quote" a regular expression.
try this
UPDATE coords SET x_pos = '".$x_coord."', y_pos = '".$y_coord."'
and look here how to use toJSON
EDIT :
try this
$.ajax({
type: "POST",
data : { coordTop: coord.top, coordLeft: coord.left ,coords: coords },
and in second code do this
$data = json_decode($_POST['data']);
$coordTop = mysql_real_escape_string($_POST['coordTop']);
$coordLeft = mysql_real_escape_string($_POST['coordLeft']);
$coords = mysql_real_escape_string($_POST['coords']);
foreach(.........
.....
.....
and then use those variables $coordTop , $coordLeft , $coords
Thanks for the help but this seemed to do the trick....
In javascript:
$.post('updatecoords.php', 'data='+$.toJSON(order), function(response){ alert (response + mydata);
In Updatecoords.php:
$data = json_decode(stripcslashes($_POST['data']));

php to js array convert with jquery's ajax

Im trying to convert 5 PHP arrays to 5 js arrays.
I used to transfer php variables to js variables with json like this:
$return['variable'] = $variable;
echo json_encode($return);
And then fetch it as json object on the js side like this:
success : function(data) {
alert(data.variable);
}
now things are a bit more complicated, i need to transfer these 5 php arrays from a php script to my js script as 5 js arrays:
PHP arrays:
$i = 0;
while ($location = mysql_fetch_array($get_locations)) {
$location_full_name[$i] = $location['loc_full_name'];
$location_main_name[$i] = $location['loc_main_name'];
$location_sub_name[$i] = $location['loc_sub_name'];
$location_anchor_id[$i] = $location['loc_anchor_id'];
$location_type[$i] = $location['loc_type'];
$i++;
}
and fill these corresponding arrays:
var location_full_name = new Array();
var location_main_name = new Array();
var location_sub_name = new Array();
var location_anchor_id = new Array();
var location_type = new Array();
i dont know how to do this. hope i can get some help :)
regards,
alexander
Maybe if you post what returns in "data" so we can help you more (i think). hehe.
I suggest, for your php code, where you set the data into the arrays:
$i = 0;
$rsl = array();
while ($location = mysql_fetch_array($get_locations)) {
$rsl[$i]['full_name'] = $location['loc_full_name'];
$rsl[$i]['main_name'] = $location['loc_main_name'];
$rsl[$i]['sub_name'] = $location['loc_sub_name'];
$rsl[$i]['anchor_id'] = $location['loc_anchor_id'];
$rsl[$i]['type'] = $location['loc_type'];
$i++;
}
echo json_encode($rsl);
So to get this on the javascript
// You could do the same... var location = []...
var location_full_name = new Array();
var location_main_name = new Array();
var location_sub_name = new Array();
var location_anchor_id = new Array();
var location_type = new Array();
...
dataType: "json",
success : function(data) {
$.each(data, function(index, arr){
location_full_name[index] = arr['full_name'];
...
});
}
For each of your arrays, store the value returned from json_encode. And/or make them one array/object and do the same.
You can utilize the PHP array that is actually an ordered map. Below is an example:
PHP:
<?php
$location_full_name = array("Google, Inc.", "Siku-Siku.com");
$location_type = array("Google headquarter", "Virtual address");
$ret = array("full_name" => $location_full_name, "type" => $location_type);
echo json_encode($ret);
?>
JavaScript (jQuery):
<script type="text/javascript">
$(function() {
$.get("test.php", function(data) {
console.log(data.full_name[1]); // Prints "Siku-Siku.com".
}, "json");
});
</script>

returning JSON and HTML from PHP script

Hi searched through the questions here, but couldn't find anything. I'm new at writing PHP and jQuery, so bear with me.
What I'm trying to do is send an ajax request using jQuery to my script which runs a mysql query on data from my database and serializes it into the JSON format using php's json_encode. The response is then parsed with the available json2.js script. All of this works fine, but I'd also like to return more data other than just JSON from this script.
mainly, i'd like to also echo the following line before the json_encode:
echo "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";
however, my jQuery is evaluating the entire response during the ajax success, making the json.parse function fail due to the script's return being in an invalid format.
success: function(data) {
//retrieve comments to display on page by parsing them to a JSON object
var obj = JSON.parse(data);
//loop through all items in the JSON array
for (var x = 0; x < obj.length; x++) {
//Create a container for the new element
var div = $("<div>").addClass("bubble").appendTo("#comments");
//Add author name and comment to container
var blockquote = $("<blockquote>").appendTo(div);
$("<p>").text(obj[x].comment).appendTo(blockquote);
var cite = $("<cite>").appendTo(div);
$("<strong>").text(obj[x].name).appendTo(cite);
$("<i>").text(obj[x].datetime).appendTo(cite);
}
$("#db").attr("value", '' + initialComments + '');
}
does anyone know how i can return the html line as well as the json_encode to use this script for more than just json population?
thankyou, this website has been wonderful in answering my noob questions.
my php:`
for ($x = 0, $numrows = mysql_num_rows($result); $x < $numrows; $x++) {
$row = mysql_fetch_assoc($result);
$comments[$x] = array("name" => stripslashes($row["name"]), "comment" => stripslashes($row["comment"]), "datetime" => date("m/d/Y g:i A", strtotime($comment['datetime'])));
}
//echo "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";
$response = json_encode($comments);
echo $response;`
Don't echo the line, save it in a variable. Construct a simple array
$response = array(
'html' => $the_line_you_wanted_to_echo,
'jsobject' => $the_object_you_were_going_to_send_back
); and send that back ( via json_encode ) instead.
Also, you don't need json2.js, jQuery has an excellent JSON parser.
you can load like this $.get( 'your/url', { params : here }, success, 'JSON' );
Changed to match your newly introduced iteration.
for ($x = 0, $num_rows = mysql_num_rows($result); $x < $num_rows; $x++) {
$row = mysql_fetch_assoc($result);
$comments[$x] = array(
"name" => stripslashes($row["name"]),
"comment" => stripslashes($row["comment"]),
"datetime" => date("m/d/Y g:i A", strtotime($comment['datetime']))
);
}
$html = "<h1 style='margin-left: 25px;'>$num_rows Comments for $mysql_table</h1>";
echo json_encode(array( 'comments' => $comments, 'html' => $html ));
then, in your javascript, you have
function success( parsedObject ){
parsedObject.html; // "<h1 style..."
parsedObject.comments; // an array of objects
parsedObject.comments[0].name
+ " on " + parsedObject.comments[0].datetime
+ " said \n" + parsedObject.comments[0].comment; // for example
}
As said above just put all the data you want to get back in an array and encode that.
<?php
echo json_encode(array(
'html' => $html,
'foo' => $bar,
'bar' => $baz
));
?>
Also as said you don't need json2.js. You can parse JSON data with any of jQuery's ajax functions by specifying the data type as json.
$.ajax({
type: 'POST',
url: 'path/to/php/script.php',
dataType: 'json',
data: 'foo=bar&baz=whatever',
success: function($data) {
var html = $data.html;
var foo = $data.foo;
var bar = $data.bar;
// Do whatever.
}
});
EDIT Pretty much what Horia said. The only other variation I could see is if you wanted everything in the same array.
For example:
PHP:
<?php
// You have your comment array sent up as you want as $comments
// Then just prepend the HTML string onto the beginning of your comments array.
// So now $comments[0] is your HTML string and everything past that is your comments.
$comments = array_unshift($comments, $your_html_string);
echo json_encode($comments);
?>
jQuery:
$.ajax({
type: 'POST',
url: 'path/to/php/script.php',
dataType: 'json',
data: 'foo=bar&baz=whatever',
success: function($comments) {
// Here's your html string.
var html = $comments[0];
// Make sure to start at 1 or you're going to get your HTML string twice.
// You could also skip storing it above, start at 0, and add a bit to the for loop:
// if x == 0 then print the HTML string else print comments.
for (var x = 1; x < $comments.length; x++) {
// Do what you want with your comments.
// Accessed like so:
var name = $comments[x].name;
var comment = $comments[x].comment;
var datetime = $comments[x].datetime;
}
}
});
You might be interested in jLinq, a Javascript library that allows you to query Javascript objects. A sample query would be:
var results = jLinq.from(data.users)
.startsWith("first", "a")
.orEndsWith("y")
.orderBy("admin", "age")
.select();
jLinq supports querying nested objects and performing joins. For example:
var results = jLinq.from(data.users)
.join(data.locations, //the source array
"location", //the alias to use (when joined)
"locationId", // the location id for the user
"id" // the id for the location
)
.select(function(r) {
return {
fullname:r.first + " " + r.last,
city:r.location.city,
state:r.location.state
};
});

Categories