Flot Chart From Database - javascript

I'm trying to implement a FLOT chart from database, but I'm having a few problems...
I have a database with 2 rows: Data, Pcr
My files .php:
Datas.php
$dates=array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$date=$row['Date'];
$pcrs=(float)$row['Pcr'];
$dates[] = array(strtotime($date)*1000,$pcrs);
}
echo json_encode($dates);
I get the array:
[[1434240000000,7.2],[1434758400000,4.83],[1443052800000,4.85],[1445817600000,4.56],[1446163200000,4.5]]
I would like to get a chart from this array, but I don't know how to do that...
I have this file, and I know that it is incomplete...
Flot.php
<script>
$(document).ready(function(){
$.ajax({
type:’post’,
dataType:'json',
url:'datas.php',
success:function(data){
var datasets = {
"pcr": {
label: "Pcr",
data: dates
}
};
Could someone help me to do this chart?
Thank you very much

Related

Google Charts (gague) display when no value in database

I want to display google chart (gauge) when there is no values in my database.
My idea for doing this is to insert a dummy value in an array to display the chart and once values are added to the database overrides it.
postData.php:
<?php require 'conn.php';?>
<?php
$sql = "SELECT * FROM sensors ORDER BY id DESC LIMIT 1";
$result = $conn->query($sql) or die ($conn->error);
// create data array
$data = [];
$data[] = [["label"=>"Label","type"=>"string"],["label"=>"Value","type"=>"number"]];
// output data of each row
while ($row = $result->fetch_assoc() {
$data[] = ["Temp", (float) $row["temp"]];
}
// write data array to page
echo json_encode($data, JSON_NUMERIC_CHECK);
$result->free();
$conn->close();
?>
index.php
<script>
google.charts.load('current', {
packages: ['gauge']
}).then(function () {
var options = {
width: 400, height: 400,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
drawChart();
function drawChart() {
$.ajax({
url: 'postData.php',
dataType: 'json'
}).done(function (jsonData) {
// use response from php for data table
var data = google.visualization.arrayToDataTable(jsonData);
chart.draw(data, options);
// draw again in 5 seconds
window.setTimeout(drawChart, 5000);
});
}
});
</script>
<div id="chart_div" class="chart_hum" style="width: 400px; height: 120px;"></div>
I solved the issue by referencing this link and adding this code. Instead of doing in PHP using an array, I used JavaScript to add the dummy value and it gets overridden once data are inserted in to the database. Hope this maybe useful to someone in the future.
function drawChart() {
$.ajax({
url: 'postData.php',
dataType: 'json'
}).done(function (jsonData) {
// use response from php for data table
var data = google.visualization.arrayToDataTable(jsonData);
// added part
if (data.getNumberOfRows() === 0) {
data.addRows([
['Temp', 0]
]);
}
chart.draw(data, options);
// draw again in 5 seconds
window.setTimeout(drawChart, 5000);
});
}

How to Display Categories in Select Box to Update the Record?

Hey Everyone Please help me, I want to update the record, but the problem is I can't see more than 1 categories in the select box. I have been using Php/MySQLi and Also Ajax.
Total Categories Stored in the Database Three
So, Please Look at that:
Here is Php Function
function get_product_record()
{
global $con;
$Pro_Update_Id = $_POST['Pro_Update_ID'];
$query = "SELECT Product.Product_ID, categories.cat_name, categories.cat_id, product.Product_Name,product.Product_Qty,product.Price,product.Description from product INNER JOIN categories on product.Category_ID=categories.cat_id where product.Product_ID='$Pro_Update_Id'";
$result = mysqli_query($con,$query);
while($row=mysqli_fetch_assoc($result))
{
$data = "";
$data[0]=$row['Product_ID'];
$data[1]=$row['cat_name'];
$data[2]=$row['Product_Name'];
$data[3]=$row['Product_Qty'];
$data[4]=$row['Price'];
$data[5]=$row['Description'];
$data[6]=$row['cat_id'];
}
echo json_encode($data);
}
Here is jQuery File
function get_pro_record()
{
$(document).on('click','#p_btn_edit',function()
{
var GetPID = $(this).attr('data-id');
$.ajax(
{
url: 'includes/products/get_pro_record.php',
method: 'post',
data:{Pro_Update_ID:GetPID},
dataType: 'JSON',
success:function(data)
{
$('#product_id').val(data[0]);
$('#cat_up_name').html('<option id="p_update_id" value='+(data[6])+'>'+(data[1])+'<option>');
$('#product_up_name').val(data[2]);
$('#up_Qty').val(data[3]);
$('#up_Price').val(data[4]);
$('#up_description').val(data[5]);
$('#products_update').modal('show');
}
})
})
}
Here is a Screenshot of the Project:

Display data from MYSQL Database to Morris.js PHP AJAX

I want to display the data from my database into a chart Morris.js to be precise. I need to choose a branch from my dropdown, when i choose a branch the total sales of that branch should be transferred to the Morris.js Bar chart. I am having a problem with transferring the data to the Bar Chart. I am using AJAX, PHP and Morris.js.
PHP Code for dropdown:
<select class="form-control" id="t-yearly">
<option value="">Branch</option>
<?php
require_once "connect.php";
$sql = "SELECT id,branch FROM tblLocation";
$result = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_array($result)) {
echo "<option value='".$row['id']."'>".$row['branch']."</option>";
}
?>
</select>
AJAX Code for chart display:
//Total Yearly Sales
$("#t-yearly").change(function(){
var branch = $(this).val();
$.ajax ({
url:"fetch_yearly_sales.php",
method: "POST",
data: {branch:branch},
success: function(branch_data){
new Morris.Bar({
element: 't-yearly-sales',
data: branch_data,
xkey: 'year',
ykeys: ['sales'],
labels: ['Total Sales'],
hideHover: 'auto'
});
console.log(branch_data);
}
});
});
PHP Code for fetch_yearly_sales.php:
<?php
require "connect.php";
$data = mysqli_real_escape_string($conn,$_POST["branch"]);
$ar = array();
if(!empty($data)){
$sql = "SELECT year, SUM(sales) AS sales FROM tblSales WHERE branch_id=".$data." GROUP BY year";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
$ar[] = array(
'year' => $row['year'],
'sales' => $row['sales']
);
}
echo json_encode($ar);
}
else if (empty($data)){
$sql = "SELECT year, SUM(sales) AS sales FROM tblSales GROUP BY year";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
$ar[] = array(
'year' => $row['year'],
'sales' => $row['sales']
);
}
echo json_encode($ar);
}
You didn't specify what problem you were experiencing, but from the code it looks like you're passing a JSON string to Morris, while it actually requires a JSON object. So try changing: data: branch_data to data: JSON.parse(branch_data). I could be wrong though, it would help if you specified what exactly wasn't working.
I suppose you need to use the function setData() instead of creating a new chart always. This updates the chart with data given in parameters. You need to change to something like this:
var branch_data = [];
var my_chart = new Morris.Bar({
element: 't-yearly-sales',
data: branch_data,
xkey: 'year',
ykeys: ['sales'],
labels: ['Total Sales'],
hideHover: 'auto'
});
$("#t-yearly").change(function(){
var branch = $(this).val();
$.ajax ({
url:"fetch_yearly_sales.php",
method: "POST",
data: {branch:branch},
dataType: "json",
success: function(branch_data){
my_chart.setData(branch_data);
}
});
});
By the way, I mentioned the dataType to JSON in the code above so that you would not need to parse the result from server.

Table has no columns - Google Charts - PHP AJAX

I started to learn how to use Google Charts today and I'm a bit stuck.
I have dynamic data (changes about 3-4 times a day) to pump into the chart (Pie Chart). I'm using AJAX as the data source and PHP as my backend.. I tried to do it this way but to no avail:
AJAX:
<?php
include $_SERVER['DOCUMENT_ROOT'].'/includes/galaxy-connect.php';
$database = new Connection();
$database = $database->Connect();
$statement = $database->Prepare(" SELECT COUNT(Membership_Level_Name) AS MemTotal, Membership_Level_Name
FROM membership AS M
LEFT JOIN membership_levels AS L
ON M.`Membership_Level_Id` = L.`Membership_Level_Id`
LEFT JOIN membership_status AS S
ON M.`MembershipStatusId` = S.MembershipStatusId
WHERE M.`MembershipStatusId` = 1
GROUP BY L.`Membership_Level_Name`
ORDER BY L.`Membership_Level_Id` ");
$statement->execute();
$MembershipTotals = $statement->fetchall(PDO::FETCH_ASSOC);
if (!empty($MembershipTotals)) {
foreach ($MembershipTotals as $MembershipTotal) {
$data[] = array(
"cols" => array("id"=>"Membership_Level_Name", "label"=>"Membership Level", "type"=>"varchar"),
array("id"=>"MemTotal", "label"=>"Total", "pattern"=>"", "type"=>"number"),
"rows" => array($MembershipTotal['Membership_Level_Name'], $MembershipTotal['MemTotal'])
);
}
}
echo json_encode($data);
so thats my ajax, and it produces:
(ok wont let me post an image but heres the results)
[{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Start Up","24"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Member","131"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Member Plus","170"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Premier Member","31"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Bronze","97"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Silver","145"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Gold","188"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Affiliate","3"]},{"cols":{"id":"Membership_Level_Name","label":"Membership Level","type":"varchar"},"0":{"id":"MemTotal","label":"Total","pattern":"","type":"number"},"rows":["Charity\/Education","4"]}]
So the next step is to call that data, I took the code from Google Charts "Connecting to a database" (or something like that) page:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "/ajax/charts/membershiptotals.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
Reload the web page and it produces the error:
Table has no columns
I don't understand why though.. I looked at other solutions and posted on Quora and the Google group for the API but to no avail.. could someone tell me whats wrong with the code??
I found the answer:
AJAX was changed to:
<?php
include $_SERVER['DOCUMENT_ROOT'].'/includes/galaxy-connect.php';
$database = new Connection();
$database = $database->Connect();
$statement = $database->Prepare(" SELECT COUNT(Membership_Level_Name) AS MemTotal, Membership_Level_Name
FROM membership AS M
LEFT JOIN membership_levels AS L
ON M.`Membership_Level_Id` = L.`Membership_Level_Id`
LEFT JOIN membership_status AS S
ON M.`MembershipStatusId` = S.MembershipStatusId
WHERE M.`MembershipStatusId` = 1
GROUP BY L.`Membership_Level_Name`
ORDER BY L.`Membership_Level_Id` ");
$statement->execute();
$MembershipTotals = $statement->fetchall(PDO::FETCH_OBJ);
$col1=array();
$col1["id"]="";
$col1["label"]="Membership Type";
$col1["pattern"]="";
$col1["type"]="string";
$col2=array();
$col2["id"]="";
$col2["label"]="Total";
$col2["pattern"]="";
$col2["type"]="number";
$cols = array($col1,$col2);
$rows=array();
foreach ($MembershipTotals AS $MembershipTotal) { //foreach ($Event->TrainingTotals['ConfirmedTotal'] AS $Key => $Value) {
$cell0["v"]=$MembershipTotal->Membership_Level_Name;
$cell1["v"]=intval($MembershipTotal->MemTotal);
$row0["c"]=array($cell0,$cell1);
array_push($rows, $row0);
}
$data=array("cols"=>$cols,"rows"=>$rows);
echo json_encode($data);
which made it a bit easier and then on the actual page:
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "/ajax/charts/membershiptotals.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 chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {title:'Membership Bookings', width: 800, height: 500});
}
</script>
Basically I had to clearly declare the columns, and the intval is to turn it into a integer, otherwise it returns the number as a string which Google doesn't like.. hope this helps anyone :)
thanks to Harish for an answer but I needed it more dynamic :-)
this is the format of the array to be passed.
javascript:
var jsondata; //json data recived from php script
var data = google.visualization.arrayToDataTable(jsondata);
php:
$data = array(
array('Membership Level', 'MemTotal'),
array('Member Plus', 170),
array('Member', 131)
);
echo json_encode($data);
Your have to pass Json array not object.

want to add custome tool tip to my line chart (tool tip will have some html content like button and some text)

I am populating the chart by getting the datatable as the response from other page.
so am creating json object at other side and transfer to the requesting site and their i parse the object and create the datatable and populating the chart.
var jsonData = $.ajax({
type: "post",
url: "getHourDrillChart.php",
data: $("#my_form").serialize(),
dataType: "json",
async: false
}).responseText;
var obj = jQuery.parseJSON(jsonData); //alert(""+obj.toSource());
var dataHour = google.visualization.arrayToDataTable(obj);\
chart.setDataTable(dataHour);
chart.setOptions(options);
chart.draw();
other site where i creating the chart data :
$data[0] = array('Hour',$user);
$getTownLocalityInfo = mysql_query($SQLString);
# set heading
//$data[0] = array('hour','Count');
$i=1;
$dayArray = array();
while( $row = mysql_fetch_assoc($getTownLocalityInfo)){
$date = $row['date'];
$hour = $row['day_hours'];
$count = (int) $row['sumCount'];
$dayArray[] = $hour;
mysql_query("INSERT INTO trend_hour_chart_temp(hour,$user,userId) VALUES ('$hour',$count,'$staffId')");
$data[$i] = array($hour , $count);
$i++;
}
echo json_encode($data);
You need to add a tooltip column to your DataTable. Add the tooltip column to your column headers first:
$data[0] = array('Hour', $user, array('type' => 'string', 'role' => 'tooltip'));
Then, in the while loop, add the tooltip data to your rows:
$data[$i] = array($hour , $count, 'tooltip string');

Categories

Resources