How to plot real time graph using php and AJAX? - php

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.

Related

passing array to javascript

I'm working on a project with a classmate, neither of us have previous experience with php and javascript. Our goal is to query a db and store the results in an array then pass that array to a javascript function. My partner wrote this bit of code which works but I was unable to successfully pass the array to our function in our javascript.
First, I tried using a local array which worked out fine when I tested it. Then I tried with the array generated in the above php segment, I've seen this question asked a few times but when I tried implementing some of the suggestions to encode the array as a JSON object that didn't work. Is there something wrong with the way we store the results from the database? I appreciate any help.
<?php
$query = "SELECT * FROM predictions ORDER BY course_no DESC";
$result = $db->query($query);
if ($result and $result->num_rows != 0) {
#$result->data_seek(0);
while($classesArray = #$result->fetch_assoc()) {
extract($classesArray);
echo $course_no . "<br>";
}
#$result->free(); // Release memory for resultset
#$db->close();
echo " <script>var a = json_encode($classesArray);</script>";
}
?>
<script>
$(document).ready(function(){
//var a = ["class1", "class2", "class3"];
//loadClasses(a);'
loadClasses(a);
});
function loadClasses(classesArray) {
// #classesfield is the id of the classes dropdown
for (var i = 0; i < classesArray.length; i++) {
$("#classesdropdown").append('<input class="w3-check" type="checkbox">'); // add checkbox to our dropdown
$label = $('<label class="w3-validate"></label>'); // crete element to inject
$label[0].innerHTML= (classesArray[i]); // give it a class label
$("#classesdropdown").append($label); // add it to our dropdown
$("#classesdropdown").append('<br>'); // add new line to the dropdown
}
}
</script>
The proper way to do this is to have a simple HTML page which requests the JSON via an AJAX call to a PHP page which in-turn fetches the Database data, processes it, and returns JSON data.
SQL Data
I made up the following data as an example, but the PHP does not care about the fields. You will just return all the data in the table as a JSON object array.
CREATE TABLE IF NOT EXISTS `course` (
`course_no` int(11) NOT NULL,
`course_name` varchar(64) NOT NULL,
`course_desc` varchar(255) DEFAULT NULL,
`course_credits` double NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `course` ADD PRIMARY KEY (`course_no`);
INSERT INTO `course` (`course_no`, `course_name`, `course_desc`, `course_credits`) VALUES
(1, 'Algebra', 'Learn how to perform basic arithmetic.', 4),
(2, 'Biology', 'Learn how to classify organisms.', 4),
(3, 'Literature', 'Read a lot of books.', 4),
(4, 'Physical Education', 'Get active!', 2);
retrieveClasses.php
Connect, query, and return the class information from the database as a JSON array.
<?php
$mysqli = new mysqli('localhost', 'admin', '', 'test');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM `course`")) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
$result->close();
$mysqli->close();
?>
index.html
Populate the dropdown with the JSON data returned from the AJAX call.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ajax Populate Using PHP DB</title>
<meta name="description" content="PHP Database Ajax Populate">
<meta name="author" content="Self">
<link rel="stylesheet" href="css/styles.css?v=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$.getJSON('./retrieveClasses.php', function(records) {
loadClasses(records.map(function(record) {
return record['course_no'] + '] ' + record['course_name'];
}));
});
});
function loadClasses(classesArray) {
// #classesfield is the id of the classes dropdown
for (var i = 0; i < classesArray.length; i++) {
$('#classesdropdown').append('<input class="w3-check" type="checkbox">'); // add checkbox to our dropdown
$label = $('<label class="w3-validate"></label>'); // crete element to inject
$label.text(classesArray[i]); // give it a class label
$('#classesdropdown').append($label); // add it to our dropdown
$('#classesdropdown').append('<br>'); // add new line to the dropdown
}
}
</script>
</head>
<body>
<div id="classesdropdown"></div>
</body>
</html>

JS and Ajax: how to dismantle JSON object consist of multiple DB records

I try to learn JS together with jQuery and Ajax, and until now it was more or less painless, but now I faced myself with some obstacles about getting result from called PHP script, initiated by Ajax. What is my problem here? I have a MySQL table and I wanted to pull some data from JS by Ajax call. I tested my query to check is it correct and make result and with same query I built PHP script. Here is my JS file:
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
</head>
<body>
<script>
callphp(12,14);
//
function callphp(par1, par2) {
$.ajax({
type: "POST",
url: "_ajax2php2.php",
cache: false,
dataType: "json",
data: { "po1": par1, "po2":par2 },
success: function(data, status, jqXHR){
jss=JSON.stringify(data);
alert(jss);
//
var strBuilder = [];
for(key in data){
if (data.hasOwnProperty(key)) {
strBuilder.push("Key is " + key + ", value is " +data[key] + "\n"); }
}
alert(strBuilder.join(""));
},
error: function(data) {
alert( "params error" );
}
});
// end of JS
and here is my PHP script:
<?php
$eol="<br/>";
$uuu= isset($_POST['po1']) ? $_POST['po1'] : '';
$zzz= isset($_POST['po2']) ? $_POST['po2'] : '';
$con=mysqli_connect("localhost","root","some_password","mydbase");
// Check connection
if (mysqli_connect_errno())
{
echo "Fail to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,"mydbase");
$query4 = "SELECT * from mytable WHERE uc_id='$uuu' AND pr_id='$zzz' ";
$result4 = mysqli_query($con, $query4);
$row4= mysqli_fetch_assoc($result4);
if(mysqli_num_rows($result4) > 1) {
while($row4[]=mysqli_fetch_assoc($result4)) {
$data = $row4; }
}
else
{$data=$row4;}
echo json_encode($data, JSON_UNESCAPED_UNICODE);
/* free result set */
mysqli_free_result($result4);
mysqli_close($con);
//end of php
?>
and it seems that it works good when PHP query return just one record, if there are 2 or more then I'm unable to "dismantle" JSON object by this JS code, because for example if my query return 3 records, in alert it appears like
Key is 0, value is [object Object]
Key is 1, value is [object Object]
Key is name_of_field1, value is 1
Key is name_of_field2, value is 12
Key is name_of_field3, value is 2
Key is name_of_field4, value is 1
Key is name_of_field5, value is 14
Key is name_of_field6, value is 2015-09-10
and I need to be able to get each particular record fields of each record in order to fill with it some HTML table. How to write this part of code that resolve JSON response consist of two or more records made by PHP? I tried examples I found here but no one met my needs. Thanks.
In your while loop after the DB query, you are just overwriting the value for $data with every iteration. I would suggest not having different logic for cases with one row in result set vs. more than one row, as this does nothing but add complexity to your code. Just return an array every time and you will be better off. Your code around the query might look like this:
$data = array();
$result4 = mysqli_query($con, $query4);
if($result4) {
while($row = mysqli_fetch_assoc($result4) {
$data[] = $row;
}
}
echo json_encode($data, JSON_UNESCAPED_UNICODE);
This simplifies this section of code and will also simplify the client-side code since now you can write it to simply expect to work with an array of objects in all cases.
This means that in javascript your code might look like (ajax success handler code shown):
success: function(data, status, jqXHR){
// data is an array, with each array entry holding
// an object representing one record from DB result set
var recordCount = data.length;
console.log(recordCount+' records returned in response.');
// you can iterate through each row like this
for(i=0;i<recordCount;i++) {
// do something with each record
var record = data[i];
// in this example, I am just logging each to console
console.log(record);
// accessing individual properties could be done like
console.log(record.name_of_field1);
console.log(record.name_of_field2);
// and so on...
}
}
You should get in the habit of using console.log() rather than alert() or similar for debugging your javascript, as alert() actually interrupts your javascript code execution and could introduce problems in debugging more complex javascript (particularly when there are asynchronous activities going on). Using the javascript console functionalty built into your browser should be fundamental practice for any javascript developer.

Data parsing from mysql into highchart with json

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.

ajax call PHP script with jQuery showing status

I am learning jQuery recently and trying to do an ajax call to a very simple PHP script, which just output 1 json text. When I just have 1 echo statement in my script, I was able to get the call working. I then tried to mimic a complex script by echo 4 json after sleep for 3 seconds each time, but this time I could not be able to make it work.
Here is my index.html:
<!DOCTYPE html>
<html>
<head>
<title>ajax</title>
<script src="jquery.js"></script>
<script src="app.js"></script>
</head>
<body>
<div id="loading"></div>
</body>
</html>
Here is my app.js:
$(function() {
$('#loading').html('<img src="http://preloaders.net/preloaders/287/Filling%20broken%20ring.gif"> loading...');
var req = $.ajax({
url: "x.php",
dataType: "json"
});
req.done(function(data) {
setTimeout(function () {
$('#loading').html(data.text);
}, 1000);
});
});
Here is my x.php:
<?php
sleep(3);
echo json_encode(array("text"=>"you got me1"));
sleep(3);
echo json_encode(array("text"=>"you got me2"));
sleep(3);
echo json_encode(array("text"=>"you got me3"));
sleep(3);
echo json_encode(array("text"=>"you got me4"));
?>
My purpose is trying to show 'you got me1', 'you got me2'...one by one after few seconds. Could anyone please help and tell me where I am doing wrong? Thanks a lot in advance.
JSON must be a monolithic string. You cannot output four separate JSON constructs in a single response. e.g.
$x = array('foo');
$y = array('bar');
$z = array('baz');
echo json_encode($x);
echo json_encode($y);
echo json_encode($z);
Will send
['foo']['bar']['baz']
across the wire. That is NOT syntactically valid JSON and will simplyl produce a parse error on the receiving end.
If you want to send 4 different chunks of data over as JSON, you'll either have to do four separate requests, or embed each response in a sub-array, e.g.
$response = array(
'x' => array('foo'),
'y' => array('bar'),
'z' => array('baz')
);
echo json_encode($response);
Remember that JSON is (almost exactly) the same as the "right-hand side" of a variable assignment in Javascript:
var foo = XXX;
^^^---json goes here
If you want your output to be accepted, you have to generate something that you could literally paste into that assignment operation and have the JS engine parse/execute it properly, so
var response = ['foo']['bar']['baz']; // syntax error
var response = [['foo'],['bar'],['baz']]; // syntactically valid

Creating jqplot graph in php page

Im trying to learn php by doing a little project using apache server. I have a php page where I want to display a bar chart with jqplot using data i pull from a MySql query. I already have a query working giving me the data i want. The problem is i dont know how to implement this into a jqplot graph. Im guessing i need to make an ajax call but if i can avoid that i would like to. my php page code so far is here http://snipt.org/oknnl2.
the javascript for the bar chart is here http://snipt.org/oknoi3.
i want the chart to render in div id=chartdiv thats on line 177. I have to visualize like 6 charts. if i can get some help on doing this one, im sure i can use the same process to build the others.
PHP cannot create the javascript plot and send it downstream to the client, but you don't have to make an actual AJAX call after the page is loaded either. Simple javascript once the page loads will suffice. If you retrieve the data you need at the PHP level, you can then make it available to javascript in the HTML received by the client. The steps to make this happen:
First, use PHP to retrieve the data you need from the MySQL database.
Then, output the plot data you retrieved using PHP inside a javascript
code block as part of the HTML that PHP sends to the client.
Execute the javascript with the data seeded by PHP on page load.
So, a simplified example:
<?php
// Retrieve plot data from mysql
$q = '...';
$r = mysql_query($q);
$plot_row1 = array();
$plot_row2 = array();
$plot_row3 = array();
while ($row = mysql_fetch_array($r)) {
// append values to $plot_row1, $plot_row2 and $plot_row3 arrays
}
$my_page_title = 'My first PHP/JS Combo Foray';
?>
<html>
<head>
<script type="text/javascript" src="/scripts/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="/scripts/my_plotter.js"></script>
</head>
<body>
<h1><?php echo $my_page_title; ?></h1>
<div id="chartdiv">
Hold on, javascript is loading the plot ...
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function() {
// we're combining the php array elements into a comma separated list
// so that when the code is output javascript thinks it's an array.
// if the $plot_row1 = array(1, 2, 3) then we'd get this:
//
// row1 = [1, 2, 3];
//
// if you needed quotes around the imploded php array values (if they
// are strings where javascript is concerned) you could do this instead:
//
// row1 = ["<?php echo substr(implode('","', $plot_row1), 0, -2); ?>"];
row1 = [ <?php echo rtrim(implode(',', $plot_row1), ','); ?> ];
row2 = [ <?php echo rtrim(implode(',', $plot_row2), ','); ?> ];
row3 = [ <?php echo rtrim(implode(',', $plot_row3), ','); ?> ];
// call your js function that creates the plot
showBrittleness(row1,row2,row3);
// add whatever js code you need to append the plot to $('#chartdiv')
}
</script>
UPDATE
According to a cursory examination of the jqplot docs, if you edit line 12 of the javascript you link from this:
var plot1 = $.jqplot('chart1', [s1, s2], {
To this:
var plot1 = $.jqplot('chartdiv', [s1, s2], {
Your function should render the plot in the 'chartdiv' id element. It seems the first argument to the $.jqplot function is the element in which to create it ...

Categories