format json data for flot graph array - javascript

I am pulling temperature sensor data from a MySQL db into a php file using the following php code:
<?php
$hostname = 'xxxxx';
$username = 'xxxxx';
$password = 'xxxxx';
$dbname="measurements";
$usertable="temperature";
try {
$dbh = new PDO("mysql:host=$hostname;dbname=measurements",
$username, $password);
/*** The SQL SELECT statement ***/
$sth = $dbh->prepare("
SELECT
ROUND(AVG(`temperature`),1) AS temperature,
TIMESTAMP(LEFT(`dtg`,16)) AS dtg
FROM `temperature`
GROUP BY LEFT(`dtg`,16)
ORDER BY `dtg` DESC
LIMIT 0,800
");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
function make_pair($date, $amount) {
return array($date, $amount);
}
$json_data = json_encode($result, JSON_NUMERIC_CHECK);
?>
I am then using javascript to plot this data in a flot graph:
<script type="text/javascript">
//put array into javascript variable
var dataset1 = <?php echo json_encode($result); ?>;
//plot
$(document).ready(function () {
$.plot($("#placeholder"), dataset1 );
});
</script>
When I open the php file in a browser and look at the javscript console I can see that the data is coming through ok and being held as the variable dataset1
It looks like this:
//put array into javascript variable
var dataset1 = [{"temperature":"19.6","dtg":"2016-07-28 12:53:00"},{"temperature":"19.5","dtg":"2016-07-28 12:52:00"},{"temperature":"19.5","dtg":"2016-07-28 12:51:00"},{"temperature":"19.6","dtg":"2016-07-28 12:50:00"},{"temperature":"19.6","dtg":"2016-07-28 12:49:00"},{"temperature":"19.6","dtg":"2016-07-28 12:48:00"},{"temperature":"19.6","dtg":"2016-07-28 12:47:00"},{"temperature":"19.6","dtg":"2016-07-28 12:46:00"},{"temperature":"19.6","dtg":"2016-07-28 12:45:00"},{"temperature":"19.6","dtg":"2016-07-28 12:44:00"},{"temperature":"19.7","dtg":"2016-07-28 12:43:00"},{"temperature":"19.7","dtg":"2016-07-28 12:42:00"},{"temperature":"19.7","dtg":"2016-07-28 12:41:00"},{"temperature":"19.7","dtg":"2016-07-28 12:40:00"},{"temperature":"19.7","dtg":"2016-07-28 12:39:00"},{"temperature":"19.7","dtg":"2016-07-28 12:38:00"},{"temperature":"19.8","dtg":"2016-07-28 12:37:00"},{"temperature":"19.8","dtg":"2016-07-28 12:36:00"},{"temperature":"19.8","dtg":"2016-07-28 12:35:00"},{"temperature":"19.8","dtg":"2016-07-28 12:34:00"},{"temperature":"19.8","dtg":"2016-07-28 12:33:00"},{"temperature":"19.8","dtg":"2016-07-28 12:32:00"},{"temperature":"19.8","dtg":"2016-07-28 12:31:00"},{"temperature":"19.8","dtg":"2016-07-28 12:30:00"},{"temperature":"19.9","dtg":"2016-07-28 12:29:00"},{"temperature":"19.9","dtg":"2016-07-28 12:28:00"},{"temperature":"19.9","dtg":"2016-07-28 12:27:00"},{"temperature":"19.9","dtg":"2016-07-28 12:26:00"},{"temperature":"19.9","dtg":"2016-07-28 12:25:00"},{"temperature":"19.9","dtg":"2016-07-28 12:24:00"},{"temperature":"20.0","dtg":"2016-07-28 12:23:00"},{"temperature":"20.0","dtg":"2016-07-28 12:22:00"},{"temperature":"20.1","dtg":"2016-07-28 12:21:00"},{"temperature":"20.1","dtg":"2016-07-28 12:20:00"},{"temperature":"20.1","dtg":"2016-07-28 12:19:00"},{"temperature":"20.0","dtg":"2016-07-28 12:18:00"},{"temperature":"20.0","dtg":"2016-07-28 12:17:00"},{"temperature":"20.0","dtg":"2016-07-28 12:16:00"},{"temperature":"20.0","dtg":"2016-07-28 12:15:00"},{"temperature":"20.0","dtg":"2016-07-28 12:14:00"},{"temperature":"20.0","dtg":"2016-07-28 12:13:00"},{"temperature":"20.0","dtg":"2016-07-28 12:12:00"},{"temperature":"20.0","dtg":"2016-07-28 12:11:00"},{"temperature":"19.9","dtg":"2016-07-28 12:10:00"},{"temperature":"20.0","dtg":"2016-07-28 12:09:00"},{"temperature":"20.0","dtg":"2016-07-28 12:08:00"},{"temperature":"20.0","dtg":"2016-07-28 12:07:00"},{"temperature":"20.0","dtg":"2016-07-28 12:06:00"},{"temperature":"19.9","dtg":"2016-07-28 12:05:00"},{"temperature":"19.9","dtg":"2016-07-28 12:04:00"},{"temperature":"19.9","dtg":"2016-07-28 12:03:00"},{"temperature":"19.9","dtg":"2016-07-28 12:02:00"},{"temperature":"19.9","dtg":"2016-07-28 12:01:00"},{"temperature":"19.9","dtg":"2016-07-28 12:00:00"},{"temperature":"19.9","dtg":"2016-07-28 11:59:00"},{"temperature":"19.9","dtg":"2016-07-28 11:58:00"},{"temperature":"19.8","dtg":"2016-07-28 11:57:00"},{"temperature":"19.8","dtg":"2016-07-28 11:56:00"},{"temperature":"19.8","dtg":"2016-07-28 11:55:00"},{"temperature":"19.8","dtg":"2016-07-28 11:54:00"},{"temperature":"19.8","dtg":"2016-07-28 11:53:00"},{"temperature":"19.7","dtg":"2016-07-28 11:52:00"},{"temperature":"19.7","dtg":"2016-07-28 11:51:00"},{"temperature":"19.7","dtg":"2016-07-28 11:50:00"},{"temperature":"19.7","dtg":"2016-07-28 11:49:00"},{"temperature":"19.7","dtg":"2016-07-28 11:48:00"},{"temperature":"19.7","dtg":"2016-07-28 11:47:00"},{"temperature":"19.6","dtg":"2016-07-28 11:46:00"},{"temperature":"19.7","dtg":"2016-07-28 11:45:00"},{"temperature":"19.6","dtg":"2016-07-28 11:44:00"},{"temperature":"19.6","dtg":"2016-07-28 11:43:00"},{"temperature":"19.6","dtg":"2016-07-28 11:42:00"},{"temperature":"19.6","dtg":"2016-07-28 11:41:00"},{"temperature":"19.6","dtg":"2016-07-28 11:40:00"},{"temperature":"19.6","dtg":"2016-07-28 11:39:00"},{"temperature":"19.6","dtg":"2016-07-28 11:38:00"},{"temperature":"19.6","dtg":"2016-07-28 11:37:00"},{"temperature":"19.6","dtg":"2016-07-28 11:36:00"},{"temperature":"19.6","dtg":"2016-07-28 11:35:00"},{"temperature":"19.6","dtg":"2016-07-28 11:34:00"},{"temperature":"19.5","dtg":"2016-07-28 11:33:00"},{"temperature":"19.5","dtg":"2016-07-28 11:32:00"},{"temperature":"19.5","dtg":"2016-07-28 11:31:00"},{"temperature":"19.5","dtg":"2016-07-28 11:30:00"},{"temperature":"19.5","dtg":"2016-07-28 11:29:00"},{"temperature":"19.5","dtg":"2016-07-28 11:28:00"},{"temperature":"19.5","dtg":"2016-07-28 11:27:00"},{"temperature":"19.5","dtg":"2016-07-28 11:26:00"},{"temperature":"19.5","dtg":"2016-07-28 11:25:00"},{"temperature":"19.5","dtg":"2016-07-28 11:24:00"},{"temperature":"19.4","dtg":"2016-07-28 11:23:00"},{"temperature":"19.4","dtg":"2016-07-28 11:22:00"},{"temperature":"19.4","dtg":"2016-07-28 11:21:00"},{"temperature":"19.4","dtg":"2016-07-28 11:20:00"},{"temperature":"19.4","dtg":"2016-07-28 11:19:00"},{"temperature":"19.4","dtg":"2016-07-28 11:18:00"},{"temperature":"19.4","dtg":"2016-07-28 11:17:00"},{"temperature":"19.4","dtg":"2016-07-28 11:16:00"},{"temperature":"19.4","dtg":"2016-07-28 11:15:00"},{"temperature":"19.4","dtg":"2016-07-28 11:14:00"},{"temperature":"19.3","dtg":"2016-07-28 11:13:00"},{"temperature":"19.3","dtg":"2016-07-28 11:12:00"},{"temperature":"19.3","dtg":"2016-07-28 11:11:00"},{"temperature":"19.3","dtg":"2016-07-28 11:10:00"},{"temperature":"19.3","dtg":"2016-07-28 11:09:00"},{"temperature":"19.3","dtg":"2016-07-28 11:08:00"},{"temperature":"19.3","dtg":"2016-07-28 11:07:00"},{"temperature":"19.3","dtg":"2016-07-28 11:06:00"},{"temperature":"19.3","dtg":"2016-07-28 11:05:00"},{"temperature":"19.3","dtg":"2016-07-28 11:04:00"},{"temperature":"19.2","dtg":"2016-07-28 11:03:00"},{"temperature":"19.2","dtg":"2016-07-28 11:02:00"},{"temperature":"19.2","dtg":"2016-07-28 11:01:00"},{"temperature":"19.2","dtg":"2016-07-28 11:00:00"},{"temperature":"19.2","dtg":"2016-07-28 10:59:00"},{"temperature":"19.2","dtg":"2016-07-28 10:58:00"},{"temperature":"19.2","dtg":"2016-07-28 10:57:00"},{"temperature":"19.2","dtg":"2016-07-28 10:56:00"},{"temperature":"19.1","dtg":"2016-07-28 10:55:00"},{"temperature":"19.1","dtg":"2016-07-28 10:54:00"},{"temperature":"19.1","dtg":"2016-07-28 10:53:00"},{"temperature":"19.1","dtg":"2016-07-28 10:52:00"},{"temperature":"19.1","dtg":"2016-07-28 10:51:00"},{"temperature":"19.1","dtg":"2016-07-28 10:50:00"},{"temperature":"19.1","dtg":"2016-07-28 10:49:00"},{"temperature":"19.1","dtg":"2016-07-28 10:48:00"},{"temperature":"19.1","dtg":"2016-07-28 10:47:00"},{"temperature":"19.1","dtg":"2016-07-28 10:46:00"},{"temperature":"19.1","dtg":"2016-07-28 10:45:00"},{"temperature":"19.0","dtg":"2016-07-28 10:44:00"},{"temperature":"19.0","dtg":"2016-07-28 10:43:00"},{"temperature":"19.0","dtg":"2016-07-28 10:42:00"},{"temperature":"19.0","dtg":"2016-07-28 10:41:00"}];
//plot
$(document).ready(function () {
$.plot($("#placeholder"), dataset1 );
});
A flot graph grid is displayed in my placeholder within the php page but no data is displayed.
If I hard code the data into the variable dataset1 using the following formatting then a graph appears.
[[1, 300], [2, 600], [3, 550], [4, 400], [5, 300]];
I believe the problem could be due to my formatting of the json data within the php section and therefore need to format it for flot graph plotting.
My apologies as I am new to flot graphs and have attempted many of the similar solutions within stackoverflow before I posted this question (my first here) but without success. Any help would be greatly appreciated!

Flot expects your dataset to be in a different format than the one you're passing in. I got it working by looping over your current dataset (your last example) to put it in the right format.
var dataset1 = [{"temperature":"19.6","dtg":"2016-07-28 12:53:00"},{"temperature":"19.5","dtg":"2016-07-28 12:52:00"},{"temperature":"19.5","dtg":"2016-07-28 12:51:00"},{"temperature":"19.6","dtg":"2016-07-28 12:50:00"},{"temperature":"19.6","dtg":"2016-07-28 12:49:00"},{"temperature":"19.6","dtg":"2016-07-28 12:48:00"},{"temperature":"19.6","dtg":"2016-07-28 12:47:00"},{"temperature":"19.6","dtg":"2016-07-28 12:46:00"},{"temperature":"19.6","dtg":"2016-07-28 12:45:00"},{"temperature":"19.6","dtg":"2016-07-28 12:44:00"},{"temperature":"19.7","dtg":"2016-07-28 12:43:00"},{"temperature":"19.7","dtg":"2016-07-28 12:42:00"},{"temperature":"19.7","dtg":"2016-07-28 12:41:00"},{"temperature":"19.7","dtg":"2016-07-28 12:40:00"},{"temperature":"19.7","dtg":"2016-07-28 12:39:00"},{"temperature":"19.7","dtg":"2016-07-28 12:38:00"},{"temperature":"19.8","dtg":"2016-07-28 12:37:00"},{"temperature":"19.8","dtg":"2016-07-28 12:36:00"},{"temperature":"19.8","dtg":"2016-07-28 12:35:00"},{"temperature":"19.8","dtg":"2016-07-28 12:34:00"},{"temperature":"19.8","dtg":"2016-07-28 12:33:00"},{"temperature":"19.8","dtg":"2016-07-28 12:32:00"},{"temperature":"19.8","dtg":"2016-07-28 12:31:00"},{"temperature":"19.8","dtg":"2016-07-28 12:30:00"},{"temperature":"19.9","dtg":"2016-07-28 12:29:00"},{"temperature":"19.9","dtg":"2016-07-28 12:28:00"},{"temperature":"19.9","dtg":"2016-07-28 12:27:00"},{"temperature":"19.9","dtg":"2016-07-28 12:26:00"},{"temperature":"19.9","dtg":"2016-07-28 12:25:00"},{"temperature":"19.9","dtg":"2016-07-28 12:24:00"},{"temperature":"20.0","dtg":"2016-07-28 12:23:00"},{"temperature":"20.0","dtg":"2016-07-28 12:22:00"},{"temperature":"20.1","dtg":"2016-07-28 12:21:00"},{"temperature":"20.1","dtg":"2016-07-28 12:20:00"},{"temperature":"20.1","dtg":"2016-07-28 12:19:00"},{"temperature":"20.0","dtg":"2016-07-28 12:18:00"},{"temperature":"20.0","dtg":"2016-07-28 12:17:00"},{"temperature":"20.0","dtg":"2016-07-28 12:16:00"},{"temperature":"20.0","dtg":"2016-07-28 12:15:00"},{"temperature":"20.0","dtg":"2016-07-28 12:14:00"},{"temperature":"20.0","dtg":"2016-07-28 12:13:00"},{"temperature":"20.0","dtg":"2016-07-28 12:12:00"},{"temperature":"20.0","dtg":"2016-07-28 12:11:00"},{"temperature":"19.9","dtg":"2016-07-28 12:10:00"},{"temperature":"20.0","dtg":"2016-07-28 12:09:00"},{"temperature":"20.0","dtg":"2016-07-28 12:08:00"},{"temperature":"20.0","dtg":"2016-07-28 12:07:00"},{"temperature":"20.0","dtg":"2016-07-28 12:06:00"},{"temperature":"19.9","dtg":"2016-07-28 12:05:00"},{"temperature":"19.9","dtg":"2016-07-28 12:04:00"},{"temperature":"19.9","dtg":"2016-07-28 12:03:00"},{"temperature":"19.9","dtg":"2016-07-28 12:02:00"},{"temperature":"19.9","dtg":"2016-07-28 12:01:00"},{"temperature":"19.9","dtg":"2016-07-28 12:00:00"},{"temperature":"19.9","dtg":"2016-07-28 11:59:00"},{"temperature":"19.9","dtg":"2016-07-28 11:58:00"},{"temperature":"19.8","dtg":"2016-07-28 11:57:00"},{"temperature":"19.8","dtg":"2016-07-28 11:56:00"},{"temperature":"19.8","dtg":"2016-07-28 11:55:00"},{"temperature":"19.8","dtg":"2016-07-28 11:54:00"},{"temperature":"19.8","dtg":"2016-07-28 11:53:00"},{"temperature":"19.7","dtg":"2016-07-28 11:52:00"},{"temperature":"19.7","dtg":"2016-07-28 11:51:00"},{"temperature":"19.7","dtg":"2016-07-28 11:50:00"},{"temperature":"19.7","dtg":"2016-07-28 11:49:00"},{"temperature":"19.7","dtg":"2016-07-28 11:48:00"},{"temperature":"19.7","dtg":"2016-07-28 11:47:00"},{"temperature":"19.6","dtg":"2016-07-28 11:46:00"},{"temperature":"19.7","dtg":"2016-07-28 11:45:00"},{"temperature":"19.6","dtg":"2016-07-28 11:44:00"},{"temperature":"19.6","dtg":"2016-07-28 11:43:00"},{"temperature":"19.6","dtg":"2016-07-28 11:42:00"},{"temperature":"19.6","dtg":"2016-07-28 11:41:00"},{"temperature":"19.6","dtg":"2016-07-28 11:40:00"},{"temperature":"19.6","dtg":"2016-07-28 11:39:00"},{"temperature":"19.6","dtg":"2016-07-28 11:38:00"},{"temperature":"19.6","dtg":"2016-07-28 11:37:00"},{"temperature":"19.6","dtg":"2016-07-28 11:36:00"},{"temperature":"19.6","dtg":"2016-07-28 11:35:00"},{"temperature":"19.6","dtg":"2016-07-28 11:34:00"},{"temperature":"19.5","dtg":"2016-07-28 11:33:00"},{"temperature":"19.5","dtg":"2016-07-28 11:32:00"},{"temperature":"19.5","dtg":"2016-07-28 11:31:00"},{"temperature":"19.5","dtg":"2016-07-28 11:30:00"},{"temperature":"19.5","dtg":"2016-07-28 11:29:00"},{"temperature":"19.5","dtg":"2016-07-28 11:28:00"},{"temperature":"19.5","dtg":"2016-07-28 11:27:00"},{"temperature":"19.5","dtg":"2016-07-28 11:26:00"},{"temperature":"19.5","dtg":"2016-07-28 11:25:00"},{"temperature":"19.5","dtg":"2016-07-28 11:24:00"},{"temperature":"19.4","dtg":"2016-07-28 11:23:00"},{"temperature":"19.4","dtg":"2016-07-28 11:22:00"},{"temperature":"19.4","dtg":"2016-07-28 11:21:00"},{"temperature":"19.4","dtg":"2016-07-28 11:20:00"},{"temperature":"19.4","dtg":"2016-07-28 11:19:00"},{"temperature":"19.4","dtg":"2016-07-28 11:18:00"},{"temperature":"19.4","dtg":"2016-07-28 11:17:00"},{"temperature":"19.4","dtg":"2016-07-28 11:16:00"},{"temperature":"19.4","dtg":"2016-07-28 11:15:00"},{"temperature":"19.4","dtg":"2016-07-28 11:14:00"},{"temperature":"19.3","dtg":"2016-07-28 11:13:00"},{"temperature":"19.3","dtg":"2016-07-28 11:12:00"},{"temperature":"19.3","dtg":"2016-07-28 11:11:00"},{"temperature":"19.3","dtg":"2016-07-28 11:10:00"},{"temperature":"19.3","dtg":"2016-07-28 11:09:00"},{"temperature":"19.3","dtg":"2016-07-28 11:08:00"},{"temperature":"19.3","dtg":"2016-07-28 11:07:00"},{"temperature":"19.3","dtg":"2016-07-28 11:06:00"},{"temperature":"19.3","dtg":"2016-07-28 11:05:00"},{"temperature":"19.3","dtg":"2016-07-28 11:04:00"},{"temperature":"19.2","dtg":"2016-07-28 11:03:00"},{"temperature":"19.2","dtg":"2016-07-28 11:02:00"},{"temperature":"19.2","dtg":"2016-07-28 11:01:00"},{"temperature":"19.2","dtg":"2016-07-28 11:00:00"},{"temperature":"19.2","dtg":"2016-07-28 10:59:00"},{"temperature":"19.2","dtg":"2016-07-28 10:58:00"},{"temperature":"19.2","dtg":"2016-07-28 10:57:00"},{"temperature":"19.2","dtg":"2016-07-28 10:56:00"},{"temperature":"19.1","dtg":"2016-07-28 10:55:00"},{"temperature":"19.1","dtg":"2016-07-28 10:54:00"},{"temperature":"19.1","dtg":"2016-07-28 10:53:00"},{"temperature":"19.1","dtg":"2016-07-28 10:52:00"},{"temperature":"19.1","dtg":"2016-07-28 10:51:00"},{"temperature":"19.1","dtg":"2016-07-28 10:50:00"},{"temperature":"19.1","dtg":"2016-07-28 10:49:00"},{"temperature":"19.1","dtg":"2016-07-28 10:48:00"},{"temperature":"19.1","dtg":"2016-07-28 10:47:00"},{"temperature":"19.1","dtg":"2016-07-28 10:46:00"},{"temperature":"19.1","dtg":"2016-07-28 10:45:00"},{"temperature":"19.0","dtg":"2016-07-28 10:44:00"},{"temperature":"19.0","dtg":"2016-07-28 10:43:00"},{"temperature":"19.0","dtg":"2016-07-28 10:42:00"},{"temperature":"19.0","dtg":"2016-07-28 10:41:00"}];
var dataset2 = [];
for (var i = 0; i < dataset1.length; i++) {
dataset2.push( [ Date.parse(dataset1[i].dtg),
parseFloat(dataset1[i].temperature) ] );
}
//plot
$(document).ready(function () {
$.plot( $("#placeholder"),
[dataset2], // wrap data series in a container
{ xaxis: { mode: "time" } }
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/flot/0.7/jquery.flot.min.js"></script>
<div id="placeholder" style="width:600px; height:400px; float: left;"></div>
After var dataset2 = [];, the loop unpacks each element in your dataset and creates a [date, temp] data point to add to the array. I had to parse both the date and the float, since Flot expects numeric data, not strings.
That creates one data series. You can plot multiple data series in Flot, so note that I had to wrap that series in another container in the call to plot. (In other words, that container could have had [dataset2, dataset3, ..., datasetX].)
The last step that was needed was to set { mode: "time" } on the x-axis.

Related

Get all data from gridmvc including all paging in javascript?

I am trying to fetch data from gridmvc and show graphs using chart.js its working fine but issue is that its showing just with pages. Because i have enabled paging in grid and when i click on next page then next grid data page graphs show, but i want to show graph of complete grid data includes all pages.
<div class="panel-body">
#await Html.Grid(Model).Columns(columns =>
{
columns.Add(c => c.ID).Titled("StudentID").Filterable(true);
columns.Add(c => c.Name).Titled("Name").Filterable(true);
columns.Add(c => c.Major).Titled("Major").Filterable(true);
columns.Add(c => c.Minor).Titled("Minor").Filterable(true);
columns.Add(c => c.Email).Titled("Email").Filterable(true);
columns.Add(c => c.Address).Titled("Address").Filterable(true);
columns.Add(c => c.GPA).Titled("GPA").Filterable(true);
}).Searchable(true, false, true).WithPaging(10).ChangePageSize(true).Sortable(true).EmptyText("No data found").Named("GridSearch").RenderAsync()
</div>
Javascript
function LoadChart() {
debugger;
var chartType = parseInt($("#rblChartType input:checked").val());
var items = $(".grid-mvc").find(".grid-table > tbody").children();
var json = [];
$.each(items, function (i, row) {
$col1=$(row).children()[0].innerText;
$col2 = $(row).children()[1].innerText;
$col3 =$(row).children()[2].innerText;
$col4 =$(row).children()[3].innerText;
$col5 =$(row).children()[4].innerText;
$col6 =$(row).children()[5].innerText;
$col7 =$(row).children()[6].innerText;
json.push({ 'StudentID': $col1, 'Name': $col2, 'Major': $col3, 'Minor': $col4, 'Email': $col5, 'Address': $col6, 'GPA': $col7
})
// Map JSON values back to label array
var labels = json.map(function (e) {
return e.Name;
});
console.log(labels); // ["2016", "2017", "2018", "2019"]
// Map JSON values back to values array
var values = json.map(function (e) {
return e.GPA;
});
var chart=BuildChart(labels, values, "Students Name by GPA");
I want to show graphs which include complete data in gridmvc not just on current page.
but issue is that its showing just with pages. Because i have enabled
paging in grid and when i click on next page then next grid data page
graphs show, but i want to show graph of complete grid data includes
all pages.
var items = $(".grid-mvc").find(".grid-table > tbody").children();
var json = [];
$.each(items, function (i, row) {
$col1=$(row).children()[0].innerText;
$col2 = $(row).children()[1].innerText;
$col3 =$(row).children()[2].innerText;
$col4 =$(row).children()[3].innerText;
$col5 =$(row).children()[4].innerText;
$col6 =$(row).children()[5].innerText;
$col7 =$(row).children()[6].innerText;
json.push({ 'StudentID': $col1, 'Name': $col2, 'Major': $col3, 'Minor': $col4, 'Email': $col5, 'Address': $col6, 'GPA': $col7
})
The issue relates the above scripts, since you implement paging, when using the above code to get the table resource, it only gets the current page records, then display the page grahps.
To solve this issue, you could get the records from the page model (Model) or create an action method to get all records, then, use JQuery Ajax method to call this method and get the grid data.
To get records from the page model, in your Asp.net Core MVC application, you could use the Json.Serialize() method to convent the Model to JSON string first, then use JSON.parse() method convent the JSON string to JavaScript Object, then loop through the Object and get all data.
Code like this (Index.cshtml)
#model List<StudentViewModel>
#section Scripts{
<script>
$(function () {
LoadChart();
});
function LoadChart() {
debugger;
//var chartType = parseInt($("#rblChartType input:checked").val());
//var items = $(".grid-mvc").find(".grid-table > tbody").children();
var json = [];
var items = JSON.parse('#Json.Serialize(Model)');
$.each(items, function (index, item) {
json.push({ 'StudentID': item.id, 'Name': item.name, 'Major': item.major, 'Major': item.major, 'Email': item.email, 'Address': item.address, 'GPA': item.gpa });
});
//show graphs based on the json array.
The screenshot like this:

anychart not taking dynamically added data

I am using anychart to draw a chart in my page, My code is like this
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.anychart.com/js/7.12.0/anychart-bundle.min.js"></script>
<link rel="stylesheet" href="https://cdn.anychart.com/css/7.12.0/anychart-ui.min.css" />
<input id="chart-charitytomoney" value="[["Charity 4",10.00],["Charity 2",20.00],["Charity Donate",100.00],["Donate Your Humanity",5920.00],["Gift your Work",3155.00],["Celebrate Baby Shower",770.00],["Refer Friends",110.00],["Gift Your Friends",200.00],["Celebrate B\u0027day With Us",220.00],["Celebrate Weekend",50.00],["Piggy Bank",4100.00],["Give a Single Gift",4050.00]]">
<div id="chart-container" style="height:550px!important"></div>
<script type="text/javascript">
$(document).ready(function(){
anychart.onDocumentReady(function () {
var data = $("#chart-charitytomoney").val();
// create column chart
chart = anychart.column();
// turn on chart animation
chart.animation(true);
// set chart title text settings
chart.title('Charities by donation');
// create area series with passed data
alert(data);
var series = chart.column(data);
// set series tooltip settings
series.tooltip().titleFormatter(function () {
return this.x
});
series.tooltip().textFormatter(function () {
return '$' + parseInt(this.value).toLocaleString()
});
series.tooltip().position('top').anchor('bottom').offsetX(0).offsetY(5);
// set scale minimum
chart.yScale().minimum(0);
// set yAxis labels formatter
chart.yAxis().labels().textFormatter("${%Value}");
// tooltips position and interactivity settings
chart.tooltip().positionMode('point');
chart.interactivity().hoverMode('byX');
// axes titles
chart.xAxis().title('Product');
chart.yAxis().title('Revenue');
// set container id for the chart
chart.container('chart-container');
// initiate chart drawing
chart.draw();
});
});
</script>
Everything looks okay to me, But chart is not working.
but if I changed this line
var data = $("#chart-charitytomoney").val();
to
var data = [["Charity 4", 10.00], ["Charity 2", 20.00], ["Charity Donate", 100.00], ["Donate Your Humanity", 5920.00], ["Gift your Work", 3155.00], ["Celebrate Baby Shower", 770.00], ["Refer Friends", 110.00], ["Gift Your Friends", 200.00], ["Celebrate B\u0027day With Us", 220.00], ["Celebrate Weekend", 50.00], ["Piggy Bank", 4100.00], ["Give a Single Gift", 4050.00]]
Everything works. Can anyone point out what I am doing wrong here? And How I can overcome it?
It is a peculiar way to pass data but you can do that, just:
Option 1
You should use quotes in the input field:
<input id="chart-charitytomoney" value="[['Charity 4',10.00],['Charity 2',20.00],['Charity Donate',100.00],['Donate Your Humanity',5920.00],['Gift your Work',3155.00],['Celebrate Baby Shower',770.00],['Refer Friends',110.00],['Gift Your Friends',200.00],['Celebrate B\u0027day With Us',220.00],['Celebrate Weekend',50.00],['Piggy Bank',4100.00],['Give a Single Gift',4050.00]]">
And you need to eval() the result:
var data = eval($("#chart-charitytomoney").val());
Here is a sample: http://jsfiddle.net/yr35w6nu/8/
However, eval is no quite secure, if you want to store data in a string in a field like this consider using code like this:
Option 2
var data = JSON.parse($("#chart-charitytomoney").val().replace(/\'/g,'\"'));
shown in this sample: http://jsfiddle.net/yr35w6nu/9/
The same may be applied to your code with &quote;:
var data = JSON.parse($("#chart-charitytomoney").val().replace(/\"/g,'\"'));
Sample parsing quotes: http://jsfiddle.net/yr35w6nu/10/
Option 3
There is also a way to store CSV formatted string:
<input id="chart-charitytomoney" value="Charity 4,10.00;Charity 2,20.00;Charity Donate,100.00;Donate Your Humanity,5920.00;Gift your Work,3155.00;Celebrate Baby Shower,770.00\nRefer Friends,110.00;Gift Your Friends,200.00;Celebrate B\u0027day With Us,220.00;Celebrate Weekend,50.00\nPiggy Bank,4100.00\nGive a Single Gift,4050.00">
and then use it:
var data = anychart.data.set($("#chart-charitytomoney").val(),{rowsSeparator: ';'});
http://jsfiddle.net/yr35w6nu/13/

PHPExcel - Render HTML markups on output

In my site I have several forms using CKEditor to store it's data. So when I export all the content, in excel I can see markups all over my document. Is there an easy way to convert those to \n or somehow have PHPExcel recognize them as breaks?
I also tried changing the export type to Excel2007 thinking that maybe Excel could just simply render the HTML markup, however when I switch types my report just crashes. So im sticking with Excel5.
Any help would be appreciated.
<?php
/** PHPExcel */
require_once '/Excelphp/Classes/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$rows=2;
$sheet=$objPHPExcel->getActiveSheet();
// Set properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
->setLastModifiedBy("Maarten Balliauw")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
//This is the hard coded *non dynamic* cell formatting
$sheet->getColumnDimension('A')->setWidth(5);
$sheet->getColumnDimension('B')->setWidth(15);
$sheet->getColumnDimension('C')->setWidth(50);
$sheet->getColumnDimension('D')->setWidth(50);
$sheet->getSheetView()->setZoomScale(90);
$sheet->getStyle('A:D') ->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
//Font Setting for the Support group title.
$Support_team = array('font'=> array('bold'=> true,'color' => array('rgb' => '4D4D4D'),'size' => 22,'name' => 'Arial'),'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER),);
//Font settings for the header cells only.
$headers = array('font'=> array('bold'=> true,'color' => array('rgb' => '4D4D4D'),'size' => 12,'name' => 'Arial'),'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER),);
//Border settings
$borders = array('borders' => array('inside'=> array('style' => PHPExcel_Style_Border::BORDER_THIN,'color' => array('argb' => '717171')),'outline' => array('style' => PHPExcel_Style_Border::BORDER_THIN,'color' => array('argb' => '717171'))));
// SQl database connections
$db = mysql_connect("localhost", "IMC_COE2", "IMC123");
mysql_select_db("IMC_COE2",$db);
$sql="select client, team_name,support_team_prime,prime_comments,support_team_backup,backup_comments,escalation1,escalation1_comments,escalation2,escalation2_comments,escalation3,escalation3_comments,escalation4,escalation4_comments,note from tbl_address ORDER BY team_name";
$result=mysql_query($sql);
$numrows=mysql_num_rows($result);
if ($numrows>0)
{
while($data=mysql_fetch_array($result))
{
//Cell Merging
$sheet
->mergeCells('B'.$rows.':D'.$rows)
->mergeCells('B'.($rows+2).':D'.($rows+2))
->mergeCells('B'.($rows+5).':D'.($rows+5))
->mergeCells('B'.($rows+10).':D'.($rows+10))
->mergeCells('C'.($rows+1).':D'.($rows+1))
->mergeCells('B'.($rows+11).':D'.($rows+11));
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('B'.($rows+1), 'Client:')
->setCellValue('B'.($rows+2), 'Support group contacts')
->setCellValue('B'.($rows+3), 'Prime:')
->setCellValue('B'.($rows+4), 'Backup:')
->setCellValue('B'.($rows+5), 'Escalations')
->setCellValue('B'.($rows+6), 'Escalation 1:')
->setCellValue('B'.($rows+7), 'Escalation 2:')
->setCellValue('B'.($rows+8), 'Escalation 3:')
->setCellValue('B'.($rows+9), 'Escalation 4:')
->setCellValue('B'.($rows+10), 'Notes');
//Format the hardcoded text
$sheet->getStyle('B'.$rows)->applyFromArray($Support_team);
$sheet->getStyle('B'.($rows+2))->applyFromArray($headers);
$sheet->getStyle('B'.($rows+5))->applyFromArray($headers);
$sheet->getStyle('B'.($rows+10))->applyFromArray($headers);
//Row height adjustments
$sheet->getRowDimension($rows+3)->setRowHeight(60);
$sheet->getRowDimension($rows+4)->setRowHeight(60);
$sheet->getRowDimension($rows+6)->setRowHeight(60);
$sheet->getRowDimension($rows+7)->setRowHeight(60);
$sheet->getRowDimension($rows+8)->setRowHeight(60);
$sheet->getRowDimension($rows+9)->setRowHeight(60);
$sheet->getRowDimension($rows+11)->setRowHeight(100);
//Cell Wraptext
$sheet->getStyle('C'.($rows+1).':D'.($rows+1))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+3).':D'.($rows+3))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+4).':D'.($rows+4))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+6).':D'.($rows+6))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+7).':D'.($rows+7))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+8).':D'.($rows+8))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+9).':D'.($rows+9))->getAlignment()->setWrapText(true);
$sheet->getStyle('B'.($rows+11).':D'.($rows+11))->getAlignment()->setWrapText(true);
//Background color on cells
$sheet->getStyle('B'.$rows.':D'.$rows)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$sheet->getStyle('B'.($rows+2).':D'.($rows+2))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$sheet->getStyle('B'.($rows+5).':D'.($rows+5))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$sheet->getStyle('B'.($rows+10).':D'.($rows+10))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$sheet->getStyle('B'.($rows+1))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+3))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+4))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+6))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+7))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+8))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+9))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
//Border range
$sheet->getStyle('B'.$rows.':D'.($rows+11))->applyFromArray($borders);
//This section is the actual data imported from the SQL database *don't touch*
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('C'.($rows+1), utf8_encode($data['client'])) //this will give cell C2.
->setCellValue('B'.$rows, utf8_encode($data['team_name'])) // this will give cell B2
->setCellValue('C'.($rows+3), utf8_encode($data['support_team_prime'])) //this will give C5
->setCellValue('D'.($rows+3), utf8_encode($data['prime_comments'])) // This will give D5
->setCellValue('C'.($rows+4), utf8_encode($data['support_team_backup'])) //This will give C6
->setCellValue('D'.($rows+4), utf8_encode($data['backup_comments'])) //This will give D6
->setCellValue('C'.($rows+6), utf8_encode($data['escalation1']))//THis will give you C8
->setCellValue('D'.($rows+6), utf8_encode($data['escalation1_comments']))//This will give you D8
->setCellValue('C'.($rows+7), utf8_encode($data['escalation2']))//This will give you C9
->setCellValue('D'.($rows+7), utf8_encode($data['escalation2_comments']))//This will give you D9
->setCellValue('C'.($rows+8), utf8_encode($data['escalation3']))//This will give you C10
->setCellValue('D'.($rows+8), utf8_encode($data['escalation3_comments']))//This will give you D10
->setCellValue('C'.($rows+9), utf8_encode($data['escalation4']))//This will give you C11
->setCellValue('D'.($rows+9), utf8_encode($data['escalation4_comments']))//This will give you D11
->setCellValue('B'.($rows+11), utf8_encode($data['note'])); //This will give you B13
$rows+=14;
}
}
// Rename sheet
$sheet->setTitle('Directory Tool Full dump');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel5)
ob_end_clean();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
$today=date("F.d.Y");
$filename = "Directory_Export-$today.xls";
header("Content-Disposition: attachment; filename=$filename");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
$objWriter->save('php://output');
exit;
?>
MS Excel has no concept of HTML Markup within a cell, it's simply a string value.... storing a value like ABC<br />DEF will simply be treated as a string containing ABC<br />DEF and not as two lines containing ABC and DEF respectively. If you want it to be treated as two lines then you need to change the <br /> to "\n". You also need to set the cell alignment to wrap.

Google visualization table not allowing HTML

I am using the Google visualization tools to show a table, but all of my HTML is being shown as a string. Here is the code:
var data = new google.visualization.DataTable()
data.setTableProperty('allowHtml', true)
data.addColumn('string','Keyword')
data.addColumn('number','<img src="http://m8app.com/assets/google-icon-8556487cd6ff3508d7bf2c4f64a0e3ad.jpg">Rank')
data.addColumn('number','Rank Change')
data.addColumn('string','Page')
data.addColumn('string','Link')
var row = 1;
while(row < thing.length){
data.addRow([
thing[row][0],
parseInt(thing[row][1],10),
parseInt(thing[row][2],10),
thing[row][3],
"<a href='"+thing[row][4]+"' target='_blank'>Search</a>"]);
row++;
}
var table = new google.visualization.Table(document.getElementById('rankInner'));
table.draw(data, {
allowHtml:true,
showRowNumber: false,
page : 'enable',
pageSize:10,
sortColumn: 2,
sortAscending:false
});
I have set 'allowHtml' to true on both the DataTable and the Table, but the table still shows the full text of the HTML rather than rendering it as html. I'd be grateful for any recommendation to try, thank you.
I tried a sample like yours in the online visualization playground, and it seems good
The only line I see you got messed up is the below line, where the indentation is wrong [quotes, double quotes. Compare with the below working one]
"<a href='"+thing[row][4]+"' target='_blank'>Search</a>"]);
link : https://code.google.com/apis/ajax/playground/?type=visualization#table
Code I tried:
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Name', 'Height', 'Dance'],
['Kuttappan', 174, true],
['Raayappan', 523, false],
["<a href='abc.com' target='_blank'>Search</a>", 86, true]
]);
// Create and draw the visualization.
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, {allowHtml:true});
}
when you run it [click on RunCode in the tool], you see the search link, and not the HTML code.
The below code for image,
data.addColumn('number','<img src="http://m8app.com/assets/google-icon-8556487cd6ff3508d7bf2c4f64a0e3ad.jpg">Rank')
is indeed showing as image only, and not HTML

Display item in legend even if value = 0 with Google Charts Tools Pie Chart

I'm using Google Charts Tools, specifically the Pie Chart.
Naturally, if a item has a value of 0, it is not displayed in the pie (since it occupies 0% of the pie). However, it doesn't display in the legend either.
How can I manipulate the initialization options to still show a 0 value item in the legend, so that users can see that the item exists, it just has a 0 value?
setting sliceVisibilityThreshold as zero will solve your problem.
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 0],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
// Create and draw the visualization.
new google.visualization.PieChart(document.getElementById('visualization')).
draw(data, {title:"So, how was your day?",
sliceVisibilityThreshold:0
});
}
​
I was recently adding the Google Charts and was facing problem in it, for Adding zero value in it.
Thanks for #ocanal, I used sliceVisibilityThreshold:0, but in some other way.
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['B-TRIPS', <?php echo $arr_get_a_org['total_trips']; ?>],
['Reimbursed', <?php echo $arr_get_a_org['reimbursed_trips']; ?>],
['Approved', <?php echo $arr_get_a_org['approved_trips']; ?>],
['Pending', <?php echo $arr_get_a_org['pending_trips']; ?>]
// ['Sleep', <?php echo $arr_get_a_org['total_trips']; ?>]
]);
var options = {
title: 'OVERVIEW',
backgroundColor:'#e2e1e0',
pieSliceText:'value',
sliceVisibilityThreshold :0
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
As the way of defining of options have changed, for more info check out Google Chart site
What I did is much sketchier but produced the results I was looking for. I'm working in the Google Apps Script editor itself and utilized an excel formula to force the 0% to show.
=IF(<formula> = 0%, 1E-20%, <formula>)
Basically, in the excel column values, if the value was 0 (or 0% in my situation), I'd replace that cell with 1-E20%. It mimics an actual value (so shows up in the legend), but the other values will still add up to 100% as this value is so miniscule it doesn't affect the pie chart.

Categories

Resources