PHP json to google chart api - javascript

I'm having trouble parsing my php generated json array to a google chart. I have included Jquery, but some how i can't figure out how to parse my json data. I run a MySQL query to retrieve data from the database. Then i encode the query result with php json_encode.
I use ajax to get the json data from my php file.
getData.php:
<?php
function get_meta_values( $key, $type = 'workout', $status = 'publish' ) {
global $wpdb;
$user_ID = get_current_user_id();
if ( empty( $key ) )
return;
$r = $wpdb->get_results(
$wpdb->prepare( "
SELECT pm.meta_value, p.post_date FROM {$wpdb->postmeta} pm
LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
INNER JOIN $wpdb->term_relationships
ON (p.ID = $wpdb->term_relationships.object_id)
INNER JOIN $wpdb->term_taxonomy
ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE pm.meta_key = '%s'
AND $wpdb->term_taxonomy.taxonomy = 'category'
AND $wpdb->term_taxonomy.term_id IN (4)
AND p.post_status = '%s'
AND p.post_type = '%s'
AND p.post_author = $user_ID
ORDER BY pm.meta_value DESC ",
$key,
$status,
$type));
if ( $r ) {
$user_ids = wp_list_pluck( $r, 'post_date' );
cache_users( $user_ids );
}
return $r;
}
$workout_history = get_meta_values( '1_rep', 'workout' );
echo json_encode($workout_history);
?>
The page that holds the chart:
<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 jsonData = $.ajax({
url: "http://localhost:41175/wp-content/themes/wordpress-bootstrap-master/getData.php",
dataType: "json",
async: false
}).responseText;
var obj = window.JSON.stringify(jsonData);
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: 'Test'
};
var chart = new google.visualization.LineChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
When i try to echo my json file it looks like this:
[
{
"meta_value":"999",
"post_date":"2014-04-12 18:21:51"
},
{
"meta_value":"1",
"post_date":"2014-04-12 18:58:20"
}
]
Any suggestions to what i am doing wrong?

https://developers.google.com/chart/interactive/docs/reference#google.visualization.arraytodatatable
Seems that your JSON dataset is incorrect for use with that method. It should be (in javascript):
var data = [
['metavalue', 'post_date'],
['999', '2014-04-12 18:21:51'],
['1', '2014-04-12 18:58:20']
]
which in JSON equals to:
[["metavalue","post_date"],["999","2014-04-12 18:21:51"],["1","2014-04-12 18:58:20"]]
As I have no clue where $workout_history is coming from I can't help you out with how get to that.

Your object graph is incorrect before you return $r do this:
$results = array();
$result[] = array_values($r);
return $result;
alternatively you can build an your array of array like this:
$results = array();
$result[] = array($r['message_type'], $r['post_date']);
return $result;

Related

How can i pass a JSON array from php to JS?

im trying to populate a morris.js chart from a set of results. In my controller I create an array of the results and use json_encode to create a json array, here is the output in my view using print_r:
{"Positive":7,"Negative":26,"Pending":786,"Contact the Clinic":242,"Misc":2}
How would I pass this to my morris.js chart to populate the chart using this data as label / value pairs? everything I try I get either a blank chart or an "undefined" variable or "NaN". Here is my controller:
function execute_search()
{
// Retrieve the posted search term.
$search_term = $this->input->post('search');
// Get results count and pass it as json:
$data = $this->search_model->count_res('$p_results_data');
$pos = 0; $neg= 0; $pen = 0; $cont = 0; $misc = 0;
foreach ($data as $item) {
if ($item['result'] === 'Positive') {
$pos++;
} elseif ($item['result'] === 'Negative') {
$neg++;
} elseif ($item['result'] === 'Pending') {
$pen++;
} elseif ($item['result'] === 'Contact the Clinic') {
$cont++;
} else {
$misc++;
}
}
$res = array("Positive"=>$pos, "Negative"=>$neg, "Pending"=>$pen, "Contact the Clinic"=>$cont, "Misc"=>$misc);
$data = json_encode($res);
// Use the model to retrieve results:
$this->data['results'] = $this->search_model->get_results($search_term);
$this->data['chart'] = $data;
$this->data['totals'] = $this->search_model->total_res('$total_res');
// Pass the results to the view.
$this->data['subview'] = ('user/search_results');
$this->load->view('_layout_admin', $this->data);
}
and my morris.js:
$results = "<?php echo $chart ?>";
new Morris.Donut({
element: 'donutEg',
data: [
$results
],
});
Any help is greatly appreciated
Assuming that your morris.js is a normal javascript file, you cannot use php there by default: The server will not parse the .js file so the php source code will appear in your javascript.
You need to either:
Put the morris.js script contents in a php page in a javascript block so that the php gets parsed;
Make an ajax request from your morris.js script to get the data from the server in a separate request;
Set up your server to parse .js files as if they are / contain php.
The last one is just to illustrate what you would need, I would not recommend doing that.
In javascript, JSON.parse is your friend, assuming you have JSON that was created by PHP's json_encode function:
$results = "<?php echo $chart ?>";
new Morris.Donut({
element: 'donutEg',
data: [
JSON.parse( $results )
],
});
OR POSSIBLY
$results = "<?php echo $chart ?>";
new Morris.Donut({
element: 'donutEg',
data: JSON.parse( $results )
});
BUT THE WAY I DO IT
In the view:
<input type="hidden" id="chartData" value='<?php echo $chart; ?>' />
In the JS (using jQuery):
var chartData = $('#chartData').val();
new Morris.Donut({
element: 'donutEg',
data: JSON.parse( chartData )
});
After looking at the documentation for morris.js, I found that this is how you can do it the right way:
// Looking at the docs for morris.js:
// http://jsbin.com/ukaxod/144/embed?js,output
// This is your data, but it's all in one json object
var chartData = JSON.parse( $('#chartData').val() );
// We need to break up that object into parts of the donut
var donutParts = [];
$.each( chartData, function(k,v){
donutParts.push({
label: k,
value: v
});
});
// Now create the donut
Morris.Donut({
element: 'donutEg',
data: donutParts
});

Get JSON format from MySql to javascript using PHP

i want to get the json format from my SQL database using PHP
here is a capture of mySql database
data.php
<?php include("include/connexion.php");
$requete = "SELECT * from statistika";
$resultat = mysql_query( $requete ) or die( mysql_error() );
$rows = array();
$total_vue = 0;
here is the php code to get the data
while( $data = mysql_fetch_assoc( $resultat ) ) {
$total_vue+=$data['temps'];
$rows[] = array(
"date" => strtotime( $data['date']) * 1000,
"value" => $data[ 'temps' ]
);
}
?>
json_encode.php
<?php
include("data.php");
echo json_encode($rows);
?>
The content of json_encode is valid and i get the json format successfully
[{"date":1439769600000,"value":"5"},{"date":1439787600000,"value":"12"},{"date":1439806631000,"value":"8"},{"date":1439821320000,"value":"18"},{"date":1439919642000,"value":"6"},{"date":1439889752000,"value":"2"},{"date":1439893260000,"value":"20"},{"date":1439906400000,"value":"9"},{"date":1429308000000,"value":"15"},{"date":1421535600000,"value":"12"},{"date":1413583200000,"value":"18"},{"date":1405634400000,"value":"6"},{"date":1439828640000,"value":"14"},{"date":1439935200000,"value":"19"},{"date":1439863200000,"value":"12"},{"date":1439884800000,"value":"18"},{"date":1439917200000,"value":"26"},{"date":1439920800000,"value":"4"},{"date":1439904320000,"value":"0"},{"date":1439907420000,"value":"1"},{"date":1439907428000,"value":"1"},{"date":1439907434000,"value":"3"},{"date":1439907437000,"value":"1"},{"date":1439907447000,"value":"8"},{"date":1439907452000,"value":"3"},{"date":1439907459000,"value":"5"},{"date":1439907469000,"value":"8"},{"date":1439907482000,"value":"10"},{"date":1439907507000,"value":"21"},{"date":1439907510000,"value":"1"},{"date":1439907519000,"value":"7"},{"date":1439907526000,"value":"5"},{"date":1439907547000,"value":"18"},{"date":1439907557000,"value":"8"},{"date":1439907560000,"value":"1"},{"date":1439907576000,"value":"3"},{"date":1439907581000,"value":"3"},{"date":1418857200000,"value":"300"},{"date":1426633200000,"value":"450"},{"date":1434578400000,"value":"500"},{"date":1424214000000,"value":"600"}]
Now i want to pass the JSON format to javascript , i am using this code
var foo = {};
foo.toString = function () { return <?php echo json_encode($rows);?> };
document.write(foo.toString);
the problem is that when printing foo.toString i get this
function () { return [{"date":1439769600000,"value":"5"},{"date":1439787600000,"value":"12"},{"date":1439806631000,"value":"8"},{"date":1439821320000,"value":"18"},{"date":1439919642000,"value":"6"},{"date":1439889752000,"value":"2"},{"date":1439893260000,"value":"20"},{"date":1439906400000,"value":"9"},{"date":1429308000000,"value":"15"},{"date":1421535600000,"value":"12"},{"date":1413583200000,"value":"18"},{"date":1405634400000,"value":"6"},{"date":1439828640000,"value":"14"},{"date":1439935200000,"value":"19"},{"date":1439863200000,"value":"12"},{"date":1439884800000,"value":"18"},{"date":1439917200000,"value":"26"},{"date":1439920800000,"value":"4"},{"date":1439904320000,"value":"0"},{"date":1439907420000,"value":"1"},{"date":1439907428000,"value":"1"},{"date":1439907434000,"value":"3"},{"date":1439907437000,"value":"1"},{"date":1439907447000,"value":"8"},{"date":1439907452000,"value":"3"},{"date":1439907459000,"value":"5"},{"date":1439907469000,"value":"8"},{"date":1439907482000,"value":"10"},{"date":1439907507000,"value":"21"},{"date":1439907510000,"value":"1"},{"date":1439907519000,"value":"7"},{"date":1439907526000,"value":"5"},{"date":1439907547000,"value":"18"},{"date":1439907557000,"value":"8"},{"date":1439907560000,"value":"1"},{"date":1439907576000,"value":"3"},{"date":1439907581000,"value":"3"},{"date":1418857200000,"value":"300"},{"date":1426633200000,"value":"450"},{"date":1434578400000,"value":"500"},{"date":1424214000000,"value":"600"}]
i don't want function () { return to appear in the output !!!
Any hints ?
thanks .
Change this line in your JS code
From
foo.toString = function () { return <?php echo json_encode($rows);?> };
To
foo.toString = '<?php echo json_encode($rows);?>';
var foo = {};
foo.toString = function () { return <?php echo json_encode($rows);?> };
document.write(foo());
You are creating foo as function so call like this you will get only json.

Problems to encode PHP data with json_encode and use it in js file

Okay, I read a bunch of questions on StackOverflow but didn't seem to solve my problem.
I have a php file like this one:
<?php
require "config.php";
try {
$conn = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);
}
catch(PDOException $e) {
die("Database connection could not be established.");
}
$conn->exec("SET NAMES UTF8");
$sql = "SELECT result.year, SUM(result.grade) AS year_total_points
FROM (
SELECT *
FROM students AS s
INNER JOIN points AS p
ON s.fn = p.student_fn
) result
GROUP BY result.year
ORDER BY year_total_points DESC";
$query = $conn->query($sql);
if($query->rowCount() > 0) {
$data = array (
"years" => [],
"years_total_points" => [],
);
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$data['years'][] = $row['year'];
$data['years_total_points'][] = $row['year_total_points'];
}
echo json_encode($data);
}
else {
echo mysql_error();
}
$conn = null;
?>
Long story short I make a query to the database and get a table with column year and column year_total_points. I want to store the data in an associative array so I can pass it to the js file. Because I later in the js file need an array of all years as strings and an array of all points also as strings, I decided to store them in an associative array. But I think that json_encode doesn't encode it as it should because executing the following code:
function success(data){
var barChartData = {
labels : data["years"],
datasets : [
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,0.8)",
highlightFill : "rgba(151,187,205,0.75)",
highlightStroke : "rgba(151,187,205,1)",
data : data["years_total_points"]
}
]
}
var ctx = document.getElementById("myChart").getContext("2d");
window.myBar = new Chart(ctx).Bar(barChartData, {
responsive : true
});
}
function error(){
alert('Error!');
}
window.onload = function(){
$.ajax({url: "http://localhost/year_comparison.php"}).done(success).error(error);
}
it says that data["years"] is undefined and I would expect it to be something like ["2011", "2012", "2013"]. Everything with the query is ok because when I added alert(data); I got a result {"years":["2011"],"years_total_points":["85.98"]}. But alert(data["years"]) says undefined. Any help to solve this issue would be greatly appreciated.

AJAX POST request is failing

Apologies for the generic title.
Essentially, when the script runs 'error' is alerted as per the jQuery below. I have a feeling this is being caused by the structuring of my JSON, but I'm not sure how I should change it.
The general idea is that there are several individual items, each with their own attributes: product_url, shop_name, photo_url, was_price and now_price.
Here's my AJAX request:
$.ajax(
{
url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1',
type : 'POST',
data : 'data',
dataType : 'json',
success : function (result)
{
var result = result['product_url'];
$('#container').append(result);
},
error : function ()
{
alert("error");
}
})
Here's the PHP that generates the JSON:
<?php
function scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country)
{
header("Access-Control-Allow-Origin: *");
$html = file_get_contents($list_url);
$doc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($html))
{
$doc->loadHTML($html);
libxml_clear_errors(); // remove errors for yucky html
$xpath = new DOMXPath($doc);
/* FIND LINK TO PRODUCT PAGE */
$products = array();
$row = $xpath->query($product_location);
/* Create an array containing products */
if ($row->length > 0)
{
foreach ($row as $location)
{
$product_urls[] = $product_url_root . $location->getAttribute('href');
}
}
$imgs = $xpath->query($photo_location);
/* Create an array containing the image links */
if ($imgs->length > 0)
{
foreach ($imgs as $img)
{
$photo_url[] = $photo_url_root . $img->getAttribute('src');
}
}
$was = $xpath->query($was_price_location);
/* Create an array containing the was price */
if ($was->length > 0)
{
foreach ($was as $price)
{
$stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue);
$was_price[] = "£".$stripped;
}
}
$now = $xpath->query($now_price_location);
/* Create an array containing the sale price */
if ($now->length > 0)
{
foreach ($now as $price)
{
$stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue);
$now_price[] = "£".$stripped;
}
}
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
$result = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
);
echo json_encode($result);
}
}
else
{
echo "this is empty";
}
}
/* CONNECT TO DATABASE */
$dbhost = "xxx";
$dbname = "xxx";
$dbuser = "xxx";
$dbpass = "xxx";
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_GET['id'];
/* GET FIELDS FROM DATABASE */
$result = mysqli_query($con, "SELECT * FROM scrape WHERE id = '$id'");
while($row = mysqli_fetch_array($result))
{
$list_url = $row['list_url'];
$shop_name = $row['shop_name'];
$photo_location = $row['photo_location'];
$photo_url_root = $row['photo_url_root'];
$product_location = $row['product_location'];
$product_url_root = $row['product_url_root'];
$was_price_location = $row['was_price_location'];
$now_price_location = $row['now_price_location'];
$gender = $row['gender'];
$country = $row['country'];
}
scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country);
mysqli_close($con);
?>
The script works fine with this much simpler JSON:
{"ajax":"Hello world!","advert":null}
You are looping over an array and generating a JSON text each time you go around it.
If you concatenate two (or more) JSON texts, you do not have valid JSON.
Build a data structure inside the loop.
json_encode that data structure after the loop.
If i have to guess you are echoing multiple json strings which is invalid. Here is how it should work:
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
// Append value to array
$result[] = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
);
}
echo json_encode($result);
In this example I am echoing the final results only once.
You are sending post request but not sending post data using data
$.ajax(
{
url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1',
type : 'POST',
data : {anything:"anything"}, // this line is mistaken
dataType : 'json',
success : function (result)
{
var result = result['product_url'];
$('#container').append(result);
},
error : function ()
{
alert("error");
}
})

Google Charts not displaying values correctly

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\": [";
}

Categories