Highchart data parsed after ajax answer - php

I received from a jquery ajax function a response like :
["{y:55,color:'red'}", "{y:21}", "{y:12}", "{y:6}", "{y:3}", "{y:3}"]
In my PHP code, I encode via json_encode in an array :
foreach($pp as $value){
$tmp[]='{y:'.round(100*$pp/$sum_pp,0).'}';
}
echo json_encode(array("tableau"=>$tmp));
I'd like to have this, to be used in my Highchart graph :
[{y:55,color:'red'}, {y:21}, {y:12}, {y:6}, {y:3}, {y:3}]
How do I have to format my array to graph my answer ? I do this way to be able to change color on one column in the serie.
Thanks for your time.

If you have the possibility to change the PHP code I would opt to output something similar to the series object used in Highcharts, see http://api.highcharts.com/highcharts#series.
That is an object which looks like this:
{
data: [y1, y2, y3],
color: '#FF0000'
}
That would make your PHP code look like this:
foreach($pp as $value){
$tmp[] = round(100*$pp/$sum_pp,0);
}
echo json_encode(array(
"data" => $tmp,
"color" => '#FF0000'
));
On a side note, filling $tmp like you did in the question is bad. A better way would be:
foreach($pp as $value){
$tmp[] = array('y' => round(100*$pp/$sum_pp,0));
}
echo json_encode(array("data"=>$tmp));
As this will create a "propper" object when parsed in your Javascript. Both examples above in my code will produce something you can use directly in Highcharts. Please note that the series parameter takes an array of series. So in your javascript you would have to do:
series: [
data: response
]
Where response is the is the the output from the json_encode in you PHP script.

Related

Get value from JSON and display it (foreach command) in PHP

Hello I've been trying to solve this by myself for a few hours now, with zero luck. I'm trying to use the foreach command in php to display a decoded value from json.
{
-car_data: {
car_id: "87",
car_cost: "62000",
So let's say I want to display the value of car_id, then below that the value of car_cost.
I need to do this using the foreach command. Please briefly explain the process. I'd greatly appreciate it!
It's not clear exactly what you're asking...
If you have a JSON object and need to do something with it server side it is completely different to if you have a JSON object and want to do something with it on the webpage.
N.B.
Your JSON object is malformed there shouldn't be a - in the names.
JSON Object
Made on the client side will look something like:
var cars = {car_data: {car_id: 87, car_cost: 62000}};
Alternatively, server side, you need to convert it to a PHP readable format:
$cars = json_decode('{"car_data":{"car_id":87,"car_cost":62000}}');
JavaScript - Client Side
for(key in cars.car_data){
console.log(key + " => " + cars.car_data[key]);
}
PHP - Server Side
foreach($cars->car_data as $key => $value){
echo "{$key} => {$value}\n";
}
$decoded = json_decode($json);
foreach($decoded->cars_data as $car){
echo $car->car_cost;
}

D3js Multi line graph convert from using CSV file

I am looking to make a multi line graph from this example.
Instead of using data from a CSV file I'm building an array of values from the database:
$token_prices = sw::shared()->prices->getForTokenID($token_id);
$token_prices_array = array();
foreach ($token_prices as $token_price) {
$token_prices_array[] = [
"date" => $token_price['date'],
"close" => $token_price['close']
];
}
$second_token_prices = sw::shared()->prices->getForTokenID(3);
$second_token_prices_array = array();
foreach ($second_token_prices as $second_token_price) {
$second_token_prices_array[] = [
"date" => $second_token_price['date'],
"close" => $second_token_price['close']
];
}
$all = array_merge($second_token_prices_array, $token_prices_array);
foreach ($all as $datapoint) {
$result[$datapoint['date']] []= $datapoint['close'];
}
Data output:
{"15-Jun-18":["8.4","0.14559"],"16-Jun-18":["8.36","0.147207"],"17-Jun-18":["8.42","0.13422"],"18-Jun-18":["8.71","0.146177"],"19-Jun-18":["8.62","0.138188"],"20-Jun-18":["8.45","0.128201"],
My issue is with plugging the data from the database in:
var tokendata = <?php echo json_encode($result) ?>;
data = tokendata;
data.forEach(function(d) {
d.date = parseTime(d.date);
d.close = +d.close;
d.open = +d.open;
});
I get an issue here "data.forEach is not a function"...
How can I fix this to use the data from the database?
Here is the Fiddle
It looks like you are embedding the results of the query php page as a JSON string -- if you want to iterate over that data as an array, you will have to parse it back into a Javascript object first.
I'm assuming that the first code snippet is running on a different server, and so the $result array is not directly available to your javascript code -- is this why you are trying to set a variable to the encoded return value? If so, it's not the best way to pull data into your page's script, but this may work for you:
var data = JSON.parse('<?php echo json_encode($result)?>');
or even:
var data = eval(<?php echo json_encode($result)?>);
Both methods assume that your result is returned as a valid json string, since there is no error checking or try/catch logic. I honestly don't know what the output of the json_encode() method looks like, so if you still can't get it working, please update your post with an example of the returned string.

Can't get it working: jQuery AJAX array to PHP

I've been experiencing a lot of trouble with my issue all afternoon. Endless searches on Google and SO haven't helped me unfortunately.
The issue
I need to send an array to a PHP script using jQuery AJAX every 30 seconds. After constructing the array and sending it to the PHP file I seemingly get stuck. I can't seem to properly decode the array, it gives me null when I look at my console.
The scripts
This is what I have so far. I am running jQuery 1.11.1 and PHP version 5.3.28 by the way.
The jQuery/Ajax part
$(document).ready(function(){
$.ajaxSetup({cache: false});
var interval = 30000;
// var ids = ['1','2','3'];
var ids = []; // This creates an array like this: ['1','2','3']
$(".player").each(function() {
ids.push(this.id);
});
setInterval(function() {
$.ajax({
type: "POST",
url: "includes/fetchstatus.php",
data: {"players" : ids},
dataType: "json",
success: function(data) {
console.log(data);
}
});
}, interval);
});
The PHP part (fetchstatus.php)
if (isset($_POST["players"])) {
$data = json_decode($_POST["players"], true);
header('Content-Type: application/json');
echo json_encode($data);
}
What I'd like
After decoding the JSON array I'd like to foreach loop it in order to get specific information from the rows in the database belonging to a certain id. In my case the rows 1, 2 and 3.
But I don't know if the decoded array is actually ready for looping. My experience with the console is minimal and I have no idea how to check if it's okay.
All the information belonging to the rows with those id's are then bundled into a new array, json encoded and then sent back in a success callback. Elements in the DOM are then altered using the information sent in this array.
Could someone tell me what exactly I am doing wrong/missing?
Perhaps the answer is easier than I think but I can't seem to find out myself.
Best regards,
Peter
The jQuery.ajax option dataType is just for the servers answer. What type of anser are you expexting from 'fetchstatus.php'. And it's right, it's json. But what you send to this file via post method is not json.
You don't have to json_decode the $_POST data. Try outputting the POST data with var_dump($_POST).
And what happens if 'players' is not given as parameter? Then no JSON is returning. Change your 'fetchstatus.php' like this:
$returningData = array(); // or 'false'
$data = #$_POST['players']; // # supresses PHP notices if key 'players' is not defined
if (!empty($data) && is_array($data))
{
var_dump($data); // dump the whole 'players' array
foreach($data as $key => $value)
{
var_dump($value); // dump only one player id per iteration
// do something with your database
}
$returningData = $data;
}
header('Content-Type: application/json');
echo json_encode($returningData);
Using JSON:
You can simply use your returning JSON data in jQuery, e.g. like this:
// replace ["1", "2", "3"] with the 'data' variable
jQuery.each(["1", "2", "3"], function( index, value ) {
console.log( index + ": " + value );
});
And if you fill your $data variable on PHP side, use your player id as array key and an array with additional data as value e.g. this following structure:
$data = array(
1 => array(
// data from DB for player with ID 1
),
2 => array(
// data from DB for player with ID 2
),
...
);
// [...]
echo json_decode($data);
What I suspect is that the data posted is not in the proper JSON format. You need to use JSON.stringify() to encode an array in javascript. Here is an example of building JSON.
In JS you can use console.log('something'); to see the output in browser console window. To see posted data in php you can do echo '<pre>'; print_r($someArrayOrObjectOrAnything); die();.
print_r prints human-readable information about a variable
So in your case use echo '<pre>'; print_r($_POST); to see if something is actually posted or not.

php json_encode + modernizr object

I'm looking for better and more robust solution for echoing out yepnope feature tests using php. The output should look something like :
{
test : Modernizr.geolocation,
yep : 'normal.js',
nope : ['polyfill.js', 'wrapper.js']
}
From an output like:
$l10n = array(
'test' => 'Modernizr.geolocation',
'yep' => "'normal.js'",
'nope' => array("'polyfill.js'", "'wrapper.js'")
);
Obviously, there is the issue of quotation marks being wrapped around the json object. I can't help but wonder if there's a different class altogether that caters to creating mixed javascript objects containing raw javascript as well as strings.
json_encode returns the JSON representation of a value, the point is JSON representation is not a javascript object, JSON is a subset of the javascript object literal, so you need to do the convert in javascript.
var l10n = <?php echo json_encode($l10n); ?>;
if (l10n.test === "Modernizr.geolocation") {
l10n.test = Modernizr.geolocation;
}

Make JSON array Flot compatible

I have some PHP code that outputs a JSON array when $.getJSON is called:
.
.
.
$data = array_combine($date_dispatched,$amount);
echo json_encode($data);
This is collected by:
$.getJSON('statistics_get.php',function(output) {
$.plot($("#graph_1"), [{
data: output,
lines: {show:true}
}]
);
});
Now, using firebug, the response I get back is of the form:
{"0":"0","1296658458000":"566","1296725534000":"789","1297072385000":"890","1297072388000":"435"}
Flot is not processing this data. I believe Flot needs it to be in the form [[1,2],[4,5],[6,9]] etc. So my question is, what is the best way of getting this JSON array into the correct form for flot to read and produce a graph.
If you look at example two here: http://php.net/manual/en/function.json-encode.php
you will see that you can have json_encode return an array instead of an associative object
Would that not be the solution rather than
var flotArr = []
var cnt=0;
for (var o in data) flotArr[cnt++]=[o,data[o]]
Don't use array_combine, since it doesn't do what you need. Doing "zip" in PHP is a little bit unpleasant, but you should be able to manage with:
function make_pair($date, $amount) {
return array($date, $amount);
}
$data = array_map('make_pair', $date_dispatched, $amount);
And then JSON-encode that.

Categories