D3js Multi line graph convert from using CSV file - php

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.

Related

Why is this giving an "undefined" status

I am trying to echo some JSON with PHP. My array which I am echoing is part static and part of it has multiple records in the array.
Code
$return_output = array();
$return_output['error'] = false;
while (($serverLog_line=fgets($fopen_serverLog))!==false) {
$return_output[] = array(
"line" => $serverLog_line,
);
}
echo json_encode($return_output);
And the Jquery echoing it
$.getJSON("https://oasis-hosting.net/panel/handlers/server_functions/get.serverLog.php?service_id=22",
function(result){
var json = result;
$.each(json, function(i, data) {
$("#gameTerminal_content").append("" + data.line + "");
})
});
Now, it does echo the results, however it will echo one result which says "undefined". Screenshot: https://gyazo.com/47d2fbef749b94585c78a79b207fa65f
Thank you
It's because you have your actual data list mixed in with the error element.
Change the structure such that the data is in its own array:
$return_output['error'] = false;
$return_output['data'] = array();
In the while:
$return_output['data'] = array(
"line" => $serverLog_line,
);
In the JavaScript, iterate only over the data list not the error element:
var json = result.data;
it is written on the command console, it writes:
"Can not read the property 'line' of null"
this means, $return_output returns null. I am not so good at php, but i think you return $return_output but you modify $return_output[].
these are looking like two different variables. this should be the reason.

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.

json encoding 2 dimension array

I have the following in php:
$query = mysql_query($sql);
$rows = mysql_num_rows($query);
$data['course_num']=$rows;
$data['course_data'] = array();
while ($fetch = mysql_fetch_assoc($query) )
{
$courseData = array(
'course_name'=>$fetch['course_name'],
'training_field'=>$fetch['training_field'],
'speciality_field'=>$fetch['speciality_field'],
'language'=>$fetch['language'],
'description'=>$fetch['description'],
'type'=>$fetch['type'],
);
array_push($data['course_data'],$courseData);
}
echo json_encode($data);
when I receive the result of this script in jquery (using post)
I log it using :
console.log(data['course_data']);
and the output is :
[Object { course_name="Introduction to C++", training_field="Engineering" , speciality_field="Software", more...}]
But I can't seem to figure out how to access the elements.
I tried
data['course_data'].course_name
data['course_data']['course_name']
Nothing worked. Any ideas
When you array_push($data['course_data'],$courseData); you are actually putting $courseData at $data['course_data'][0] and therefore you would access it in JavaScript as data['course_data'][0]['course_name'].
If you only intend to have one result, instead of array_push($data['course_data'],$courseData); you should just specify $data['course_data'] = $courseData. Otherwise, you should iterate over data['course_data'] like so:
for (i in data['course_data']) {
console.log(data['course_data'][i]['course_name']);
}
You should specify the index in the first array for instance
data['course_data'][0]['course_name'];
you could make it better if you had defined the first array just as variable not a variable within an array
$data['course_data'][0]['course_name']
should do the trick. If not please send the output of var_dump($data)
Assuming the PHP code is correct, you will receive a JSON data like:
{
"course_num":34,
"course_data":[
{
"course_name":"name_value",
....
},
....etc (other object based on SQL result)
]
}
So, if you want to access to the total number of result:
data.course_num
If you want to access to the first element of the list of result:
data.course_data[0]
If you want to access to the name of the first element of the list of result:
data.course_data[0].course_name
or
data.course_data[0]['course_name']
use jquery's parseJSON method to get all the goodies out of the json object...
http://api.jquery.com/jQuery.parseJSON/

Parsing JSON in PHP

I´ve got the following JSON string:
{"Data":{"Recipes":{"Recipe_5":{"ID":"5","TITLE":"Spaghetti Bolognese"},"Recipe_7":{"ID":"7","TITLE":"Wurstel"},"Recipe_9":{"ID":"9","TITLE":"Schnitzel"},"Recipe_10":{"ID":"10","TITLE":null},"Recipe_19":{"ID":"19","TITLE":null},"Recipe_20":{"ID":"20","TITLE":"Hundefutter"},"Recipe_26":{"ID":"26","TITLE":"Apfelstrudel"},"Recipe_37":{"ID":"37","TITLE":null},"Recipe_38":{"ID":"38","TITLE":"AENDERUNG"},"Recipe_39":{"ID":"39","TITLE":null},"Recipe_40":{"ID":"40","TITLE":"Schnitzel"},"Recipe_42":{"ID":"42","TITLE":"Release-Test"},"Recipe_43":{"ID":"43","TITLE":"Wurstel2"}},"recipes_id":{"ranking_1":"9","ranking_2":"10","ranking_3":"7","ranking_4":"5"}},"Message":null,"Code":200}
How can I parse it in PHP and extract a list of TITLEs?
You can use the function json_decode to parse JSON data in PHP (>= 5.2.0, at least). Once you have a PHP object, it should be easy to iterate over all recipes/members and access their titles, using something like this:
$data = json_decode($json, true); // yields associative arrays instead of objects
foreach ($data['Data']['Recipes'] as $key => $recipe) {
echo $recipe['TITLE'];
}
(Sorry I can't actually run this code right now. Hope it helps anyway.)
If you want to do that in JavaScript, you can simply access JSON data like "normal" objects:
var jsonData = {
"Data": {"Recipes": {"Recipe_5": {"ID":"5","TITLE":"Spaghetti Bolognese"}}}
// more data
};
alert(jsonData.Data.Recipes.Recipe_5.TITLE);
This will print the TITLE of Recipe_5 in a message box.
EDIT:
If you want all the titles in a list, you can do something like this:
var titles = [];
for (var key in jsonData.Data.Recipes) {
var recipe = jsonData.Data.Recipes[key];
titles.push(recipe.TITLE);
}
alert(titles);

How to deserialize this string into a PHP array of key => value pairs?

I'm calling the script at: http://phat-reaction.com/googlefonts.php?format=php
And I need to convert the results into a PHP array format like the one I'm currently hard coding:
$googleFonts = array(
"" => "None",
"Abel"=>"Abel",
"Abril+Fatface"=>"Abril Fatface",
"Aclonica"=>"Aclonica",
etc...
);
The php returned is serialized:
a:320:{
i:0;
a:3:{
s:11:"font-family";
s:32:"font-family: 'Abel', sans-serif;";
s:9:"font-name";
s:4:"Abel";
s:8:"css-name";
s:4:"Abel";
}
i:1;
a:3:{
s:11:"font-family";
s:38:"font-family: 'Abril Fatface', cursive;";
s:9:"font-name";
s:13:"Abril Fatface";
s:8:"css-name";
s:13:"Abril+Fatface";
}
etc...
How can I translate that into my array?
You can do this by unserializing the data (using unserialize()) and then iterating through it:
$fonts = array();
$contents = file_get_contents('http://phat-reaction.com/googlefonts.php?format=php');
$arr = unserialize($contents);
foreach($arr as $font)
{
$fonts[$font['css-name']] = $font['font-name'];
}
Depending on what you're using this for, it may be a good idea to cache the results so you're not fetching external data each time the script runs.
Use unserialize(): http://www.php.net/unserialize

Categories