Data parsing from mysql into highchart with json - php

new to this and (nearly) desperated. What i want to do is the following:
read temp from sensor (works, returns float)
save data in mysql database boxklima.sensorid (works - table is boxklima.0414604605ff) in sets of date-temp pairs the date is stored as 2014-01-01 09:00:00 (datetime) and the temp as 12.123 (real)
graph data as x-axis: date y-axis: temp (totally messed this up)
So i stick to highcharts which looks nice and seems be easy to set up because everything happens client-side (except data-parsing).
Now I dont't know exactly how do create the array which is given to highchart. It should look something like this (content of create-graph.html)
<!DOCTYPE html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script‌​>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: [{}]
};
$.getJSON('data.php', function(data) {
options.series[0].data = temp;
var chart = new Highcharts.Chart(options);
});
});
</script>
Parse the data with the data.php (content shown below) from the sql-server, should generate the data on call, right?
<php>
$dbc = mysqli_connect("localhost", "pi", "pi", "boxklima");
$query = "SELECT date,temp FROM 0414604605ff";
$data = mysqli_query($dbc, $query);
$i=0;
while($row = mysqli_fetch_array($data)) {
$rows[$i]=array($row['date'],$row['temp']);
$i++;
}
echo json_encode($rows);
</php>
Opening (in browser) of data.php just shows
$dbc = mysqli_connect("localhost", "pi", "pi", "boxklima"); $query = "SELECT date,temp FROM 0414604605ff"; $data = mysqli_query($dbc, $query); $i=0; while($row = mysqli_fetch_array($data)) { $rows[$i]=array($row['date'],$row['temp']); $i++; } echo json_encode($rows);
Opening create-graph.html results in empty screen.
Credentials set to 755, the php-file has execution bit set, to. Files are in the same directory.
Help appreciated, thank you in advance, i'am lost in information and definitly puzzled.
Read through the other topics but since I'am new to this it gives me only little chunks which I was not able to match together. :S
Further information:
lighttpd/1.4.31
PHP Version 5.4.36-0+deb7u1
additional config files parsed
/etc/php5/cgi/conf.d/10-pdo.ini, /etc/php5/cgi/conf.d/20-gd.ini,
/etc/php5/cgi/conf.d/20-mcrypt.ini, /etc/php5/cgi/conf.d/20-mysql.ini,
/etc/php5/cgi/conf.d/20-mysqli.ini, /etc/php5/cgi/conf.d/20-pdo_mysql.ini
json support enabled
json version 1.2.1
mysql Client API version 5.5.40

Change your php file to this:
<?php
$dbc = mysqli_connect("localhost", "pi", "pi", "boxklima");
$query = "SELECT date,temp FROM 0414604605ff";
$data = mysqli_query($dbc, $query);
$i=0;
while($row = mysqli_fetch_array($data)) {
$rows[$i]=array($row['date'],$row['temp']);
$i++;
}
echo json_encode($rows);
?>
In create-graph.html, 'temp' variable is undefined.(You may open JavaScript Console and check for JavaScript errors)This is the reason why that page is blank.
Looking at your data.php file, I think the 'data' variable in callback function of $.getJSON would have structure like following:
[
[2014-01-01 09:00:00, 12.43]
[2014-01-02 09:00:00, 13.57]
]
Basically Array of Arrays.
So changing your function to this might help:
$.getJSON('data.php', function(data) {
dataTemp = [];
for(i=0;i<data.length;i++){
dataTemp.push(data[i][1]); // '1' index for getting that temp value. '0' for date.
}
options.series[0].data = dataTemp;
var chart = new Highcharts.Chart(options);
});
Also Please post the contents of data.php when you open it in web browser.
Also mention the JavaScript Console Error(if you get) when you open create-graph.html after making the changes.

You need to convert your string dates to timestamp and set datetime type of xAxis. To help, see strtotime function and apply in to your PHP script.

Related

Fetch data from database in JS file

I've created a tag input for my user in my site, for that purpose I coded a tag function with dropdown help. So my problem is that, I want to fetch data from data base in JavaScript file.
Js
var FormSamples = function () {
return {
//main function to initiate the module
init: function () {
// use select2 dropdown instead of chosen as select2 works fine with bootstrap on responsive layouts.
$('.select2_category').select2({
placeholder: "Select an option",
allowClear: true
});
$('.select2_sample1').select2({
placeholder: "Select a State",
allowClear: true
});
$(".select2_sample2").select2({
placeholder: "Type to select an option",
allowClear: true,
minimumInputLength: 1,
query: function (query) {
var data = {
results: []
}, i, j, s;
for (i = 1; i < 5; i++) {
s = "";
for (j = 0; j < i; j++) {
s = s + query.term;
}
data.results.push({
id: query.term + i,
text: s
});
}
query.callback(data);
}
});
function format(item) {
opt = $(item.element);
sel = opt.text();
og = opt.closest('optgroup').attr('label');
return og+' | '+item.text;
}
$("select").select2({
formatSelection: format,
escapeMarkup: function(m) { return m; }
});
$(".select2_sample3").select2({
tags: ['Karachi','Lahore']
});
}
};
}();
In the end of JS file you'll see:
$(".select2_sample3").select2({
tags: ['Karachi','Lahore']
});
Instead of "Karachi","Lahore" I want to fetch tags from data base.
I am fetching data like this:
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql = "SELECT * FROM tags";
$result = mysqli_query($conn, $sql);
mysqli_query ($conn,"set character_set_results='utf8'");
$row = mysqli_fetch_assoc($result);
Any body please help me that how can I fetch data in JS by PHP.
You can use json_encode in php:
$ar = array('Karachi','Lahore');
echo json_encode($ar);
and in javascript:
<script type="text/javascript">
// pass PHP variable declared above to JavaScript variable
var ar = <?php echo json_encode($ar) ?>;
</script>
output:
['Karachi','Lahore']
You are almost there. Now you can access the relevant data members of $row by selecting based on column name. For example you can look at the value of ˚$row["id"]. Also fetch_assoc type functions work row by row, so you will have to run it for each row, not each column, when you have multiple results. You can store the results in a php array but you will have to output them to the javascript portion of your file, or store them in a file javascript can access, before ending the php portion of your script. Below I write a little about each of your options.
Save data obtained form php data query to csv file, from which javascript can read.
Take a look at this SO post to learn how you can read data from csv. So in this example, your php script could read data from a database and then generate, via php, a csv file. Your javascript could then read from the csv file.
Alternately you can write from php directly to the javascript encoded in the same page assuming you can use your script in the same web page and not as a .js include. In that case, you can use json_encode to print your php arrays to javascript arrays as described in this SO post.
For example, to create two arrays accessible in Javascript of cities and countries I would do this:
<?php
...
$city = array();
$country = array();
while($row = mysqli_fetch_assoc($result)){
array_push($city, $row['city']);
array_push($country, $row['country']);
}
...?>
<script>
var city = <?php echo json_encode($city); ?>;
var country = <?php echo json_encode($country); ?>;
...
</script>
Here I am assuming you stored the data in a database with column names 'city' and 'country'
You should also consider using PDO objects for safer SQL manipulation.

JavaScript PHP HighChart transform a PHP array to a javascript array

I saw other posts but it doesn't work. I am a bit confused here on how I implement an array into JS from PHP...
In the PHP file (test.php) I have :
$table = array();
while($row = mysqli_fetch_assoc($result) )
{
$value=$row['value'];
$date=$row['date'];
$table[$value]=$date;
}
And in JavaScript I have :
<?php include 'test.php'; ?>
...
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
So what I look for is to put $value=$row['value']; in the y : and $date=$row['date']; in the x : OR perhaps putting the entire table $table in the var data will work also .
I'm new to JavaScript, so thanks in advance..!
So in your php file....
Add a line at the bottom that converts the table to json data.
And give it a variable...
$table = array();
while($row = mysqli_fetch_assoc($result) )
{
$value=$row['value'];
$date=$row['date'];
$table[$value]=$date;
}
$jsondata = json_encode($table);
Then in your other file....
echo that variable into your data object, in the javascript.
Remember to remove that whole random number generating function...(its just an example)
Echoing PHP into javascript is definitely not considered good practice though.
And it would be better to actually do an ajax call to your php file, and insert like that....I'll also show you how to do ajax.
<?php include 'test.php'; ?>
...
data: [<?php echo $jsondata;?>], //remove that function that was here..
// it was just to generate random numbers for the demo
....
}
EDIT / UPDATE For ajax...
So for ajax...instead of assigning a variable to $jsondata.
Just return it like so...(in your PHP file)
return json_encode($table);
Then for this way....you dont include('test.php') like you did before.
Instead you just have this script inside your $(document).ready(function(){....
$.getJSON('test.php', function(myJSON) {
//and inside this function you put your highcharts stuff...
//remove that function() that generates random data
// And you will put the 'myJSON' return object inside the 'data':[] array...
// Provided you have structured your data correctly for highcharts, it should work...
// If not.... it'll be a start, and you're well on your way to debugging it
}

How to plot real time graph using php and AJAX?

I am a newbie in web development. I have just started programming in php. I want to develop a dynamic page that is connected to MySQL database (from a server) and display the result in a plot (could be scatter, histogram) in real time. So far I managed to get my data from my database and display the graph. However, I couldn't manage to do it in real time.
I have been searching around. What I found was using AJAX to do the real time plot. Fine, I did some tutorial on it and was able to run the examples. My challenge is to plot the graph.
If it helps, this is exactly what I want to do
http://jsxgraph.uni-bayreuth.de/wiki/index.php/Real-time_graphing
I have tried to run this code but I was not able to.
Could anyone give me how to start from simple? I will elaborate if my question is not clear enough.
Thank you in advance!
#Tim, here is what I tried to do.
My php is
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
//echo "Database Connected!";
mysql_select_db("DB", $con);
$sql=mysql_query("SELECT Def_ID, Def_BH FROM BBB WHERE Ln_Def < 1200");
$Def_ID= array();
$Def_BH = array();
while($rs = mysql_fetch_array($sql))
{
$Def_ID[] = $rs['Def_ID'];
$Def_BH [] = $rs['Def_BH '];
}
mysql_close($con);
$json = array(
'Def_ID' => $Def_ID,
'Def_BH' => $Def_BH
);
echo json_encode($json);
?>
The output is
{"Df_ID":["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41"],"Df_BH":["1","1","1","5","5","2","1","1","1","1","2","1","1","1","1","1","1","1","1","1","1","1","2","1","1","2","1","3","10","1","2","1","1","1","2","2","2","1","1","1","1","1"]}
Then my script follows
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Example: Real-time updates</title>
<link href="../examples.css" rel="stylesheet" type="text/css">
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../../excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="../../jquery.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script>
<script language = "javascript" type="text/javascript" src="Include/excanvas.js"></script>
</head>
<body>
<div id="placeholder" style="width:600px;height:300px"></div>
</body>
<script type="text/javascript">
function doRequest(e) {
var url = 'fakesensor.php'; // the PHP file
$.getJSON(url,data,requestCallback); // send request
}
function requestCallback(data, textStatus, xhr) {
// // you can do stuff with "value" here
$.each(data, function(index, value) {
console.log(value.Df_ID);
console.log(value.Df_BH);
});
}
</script>
</html>
I would like to plot Def_Id versus Def_BH. Do you see what have gone wrong?
Look at High Charts Dynamic Update ;-)
First, you need to get the output right. In my opinion, JSON is the best format to transfer data between server and client using async requests. It's a data format that can be parsed easily by a lot of programming languages.
Next, you need to figure out what you are going to transfer. Are you going to transfer a bulk of data at once and animate it using javascript, or are you planning to send a request per new bit?
My advice: make the amount of requests as little as possible. Requests are slow.
How do you know what to send? Are you going a timestamp? An ID? Anything is possible. Because ID's auto-increment, you might as well use that.
So first, I'm going to set up my PHP:
// get user input
$lastID = intval($_GET['lastid']);
// --------------------------------
// FETCH RECORDS FROM DATABASE HERE
// --------------------------------
// $sql = "SELECT * FROM `graph` WHERE `id` > " . $lastID;
// CREATE DUMMY CONTENT
$data = array();
for($i = $lastID; $i < $lastID + 50; $i++) {
array_push($data, array(
'id' => $i,
'position' => array(
'x' => $i,
'y' => mt_rand(0, 10) // random value between 0 and 10
)
));
}
// END CREATING DUMMY CONTENT
// create response
$json = array(
'lastID' => $data[count($data) - 1]['id'],
'data' => $data
);
// display response
echo json_encode($json);
As you can see, I'm getting a bulk of data using lastid as input. That input is important.
Now, we are going to set up our javascript to get the request. I'm using the jQuery library for my AJAX requests because I'm a jQuery fanboy!
var interval = setInterval(doRequest, 4000); // run "doRequest" every 4000ms
var lastID = 0; // set 0 as default to ensure we get the data from the start
function doRequest(e) {
var url = 'my-file.php'; // the PHP file
var data = {'lastid': lastID}; // input for the PHP file
$.getJSON(url, data, requestCallback); // send request
}
// this function is run when $.getJSON() is completed
function requestCallback(data, textStatus, xhr) {
lastID = data.lastID; // save lastID
// loop through data
$.each(data, function(index, value) {
// you can do stuff with "value" here
console.log(value.id); // display ID
console.log(value.position.x); // display X
console.log(value.position.y); // display Y
});
}
All that remains is outputting the results to a graph!
When you look at your PHP response you'll see that there's one object with two properties containing an array.
{
"Df_ID": [1, 2, 3, ...],
"Df_BH": [1, 2, 3, ...]
}
You can access these properties by... calling those properties data.Df_ID, data.Df_BH
function requestCallback(data, textStatus, xhr) {
console.log(data.Df_ID, data.Df_BH);
}
These are what i found in google -
http://www.makeuseof.com/tag/add-graphs-php-web-app-pchart/
http://www.ebrueggeman.com/phpgraphlib
You could create dynamic graphs and call using AJAX infinitely.

creating dynamic charts using google charts, mysql, and php

I need some help. I want to create a dynamic line chart using Google's chart api and data obtained via MySql. I'm using PHP to create the pages. I was able to create a simple chart with hard-coded values no problem. Now I am trying to use some MySql data instead, but with no luck. My webpage looks like this:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var jsonData = $.ajax({
url: "graphData.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 options = {'title':'Ticket Sales',
'width':500,
'height':400};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
</script>
<?
PrintHeader($buf,$username,$userid,$session);
echo("<div id='chart_div'></div>");
?>
</html>
Then my graphData.php page looks like this:
$sql = "SELECT MONTHNAME(DATE_SOLD), COUNT(*) FROM TICKET_SALES WHERE YEAR(DATE_SOLD) = 2012 GROUP BY MONTHNAME(DATE_SOLD) ORDER BY MONTH(DATE_SOLD);";
$result = mysql_query($sql, $conn) or die(mysql_error());
//start the json data in the format Google Chart js/API expects to recieve it
$JSONdata = "{
\"cols\": [
{\"label\":\"Month\",\"type\":\"string\"},
{\"label\":\"Ticket Sales\",\"type\":\"number\"}
],
\"rows\": [";
//loop through the db query result set and put into the chart cell values
while($row = mysql_fetch_row($result))
{
$JSONdata .= "{\"c\":[{\"v\": " . $row[0] . "}, {\"v\": " . $row[1] ."}]},";
}
//end the json data/object literal with the correct syntax
$JSONdata .= "]}";
echo $JSONdata;
?>
When I load the page in my browser I just get a red box that says "Table has no columns." Can anyone tell me what I am doing wrong? Or perhaps a better/easier method? Any help would be greatly appreciated!!
Do not construct the JSON data that way, create a PHP array and use json_encode() to send the data back.
<?php
$sql = "SELECT MONTHNAME(DATE_SOLD), COUNT(*) FROM TICKET_SALES WHERE YEAR(DATE_SOLD) = 2012 GROUP BY MONTHNAME(DATE_SOLD) ORDER BY MONTH(DATE_SOLD);";
$result = mysql_query($sql, $conn) or die(mysql_error());
//start the json data in the format Google Chart js/API expects to recieve it
$data = array('cols' => array(array('label' => 'Month', 'type' => 'string'),
array('label' => 'Ticket Sales', 'type' => 'string')),
'rows' => array());
while($row = mysql_fetch_row($result)) {
$data['rows'][] = array('c' => array(array('v' => $row[0]), array('v' => $row[1])));
}
echo json_encode($data);
I have not checked the JSON output is what is wanted, only made it the same as what you were trying to generate. Also, you should get the die() to return an invalid state in a JSON object, so you can tell it failed.
Yes, use the json_encode function. It will save you lots of headaches. I'd also make sure you run your numbers through an intval() or something.
My experience with the Google charts API is that if you send a number in quotes, the chart will fail to draw, so the data types in your PHP array must be correct so the json_encode result is correct in syntax.

Displaying values from a database (using mySQL) on a Flot graph

I'm trying to read in values from a db using php (mySQL) then have them show on a graph in flot. I know the values are read in correctly and I'm not getting any errors but the graph won't show.
Little help?
Thanks in advance.
<?php
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$graphdata[] = array( (int)$row[0], (int)$row[1] );
}
?>
/////
<div id="placeholder" style="width:600px;height:300px"></div>
<script language="javascript" type="text/javascript">
var dataset1 = <?php echo json_encode($graphdata);?>;
var data = [
{
label: "Random Values",
data: dataset1
}
];
var plotarea = $("#placeholder");
$.plot( plotarea , data);
</script>
The contents of your pastebin show that the JSON string you're outputting is invalid JSON.
var data = [{ label: "Random Values",data: dataset1}];
will validate if it's changed to:
var data = [{"label": "Random Values","data": "dataset1"}]
That's just an example, but I suspect that Flot is looking for a slightly different format, so you'll have to verify exactly what they're looking for against their documentation. I'm going through the same exercise right now with FusionCharts, so I'm feeling your pain. jsonlint.com is your friend on this one, output your JSON and verify it frequently. I'd also recommend that to initially get it working, start with just a string of JSON (even one that you copy from their examples) that you put right in your code. Get the chart working first, then work on getting your PHP to duplicate the example JSON string separately.
Try delaying creating the graph until the DOM is loaded:
jQuery(document).ready(function ($){
var plotarea = $("#placeholder");
$.plot( plotarea , data);
});

Categories