I want to show on the chart the number of new students registered and the number of online students per month. I got the data but I don't know how to transfer data into js file to draw that chart.
Here is js file.
var chart = document.getElementById('products-sales');
let newStudent = $("#monthNewStudent").val();
let onlStudent = $("#monthOnline").val();
var newStudentArr = newStudent.split(",");
var onlStudentArr = onlStudent.split(",");
let arrNew = JSON.parse(newStudentArr);
let arrOnl = JSON.parse(onlStudentArr);
arrData = [];
for (var i in arrNew) {
arrData.push({
month:i,
newStudent: arrNew[i],
onlStudent: arrOnl[i]
});
}
var months = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];
Morris.Area({
element: 'products-sales',
data: [{
month: '2017-01',
newstudent: 0,
online: 0,
}],
xkey: 'month',
ykeys: ['newstudent', 'online'],
labels: ['Học viên mới', 'Học viên online'],
xLabelFormat: function(x) { // <--- x.getMonth() returns valid index
var month = months[x.getMonth()];
return month;
},
dateFormat: function(x) {
var month = months[new Date(x).getMonth()];
return month;
},
behaveLikeLine: true,
ymax: 300,
resize: true,
pointSize: 0,
pointStrokeColors:['#00B5B8', '#FA8E57', '#F25E75'],
smooth: true,
gridLineColor: '#E4E7ED',
numLines: 6,
gridtextSize: 14,
lineWidth: 0,
fillOpacity: 0.9,
hideHover: 'auto',
lineColors: ['#00B5B8', '#FA8E57', '#F25E75'],
data:arrData
});
My controller to count the number of new students registered and the number of online students per month
class DashboardController extends AdminBaseController
{
public function index ()
{
$month = 1;
$studNew = [];
$studOnline = [];
$studActive = [];
for($i = $month; $i < 13; $i++) {
//count new students
$newStudents = Member::where('member_type_id',1)->whereMonth('created_at', $i)->get();
$studNew[$i] = $newStudents->count();
//students online
$onlStudents = Member::where('member_type_id',1)->whereMonth('updated_at', $i)->get();
$studOnline[$i] = $onlStudents->count();
// count card active
$act = Order::where('status', "active")->whereMonth('updated_at', $i)->get();
$studActive[$i] = $act->count();
}
$monthNewStudent = json_encode($studNew);
$monthOnline = json_encode($studOnline);
$monthActive = json_encode($studActive);
return view('admin.dashboard.index', compact('monthNewStudent',
'monthOnline',
'monthActive'));
}
}
You can set values in a variable and then can pass that variable to view. At view, you can use that variable like below:
{!! $yourvariable !!}
So in your case, it will be like this:
data: {!! $yourvariable !!},
Hope it helps you!!
Related
I tried to display data from the database to be displayed in Full Calendar, but the data would not appear in fullcalendar, I have tried to see references in several web tutorials that integrate this, but it still hasn't worked
my reference :
https://www.patchesoft.com/fullcalendar-with-php-and-codeigniter
https://www.brianrevie.com/how-to-add-full-calendar-codeigniter
How To show fetch events from database with time in fullcalendar
I have the following data
[{"title": "Work", "start": "2019-08-01", "end": "2019-08-01" },{"title": "Work", "start": "2019-08-02","end": "2019-08-02"}]
this my js
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: [ 'dayGrid' ],
height: 440,
editable: true,
eventSources: [
{
color: '#306EFE',
textColor: '#ffffff',
events: "<?= base_url('UserDashboard/getAbsen'); ?>"
// events: [{
// title: 'My Big Event',
// start: '2019-12-09',
// end: '2019-12-10'
// },
// {
// title: 'My Second Big Event',
// start: '2019-12-11',
// end: '2019-12-13'
// },
// {
// title: 'My Second Big Event',
// start: '2019-11-11',
// end: '2019-11-13'
// },]
}
]
});
calendar.render();
});
this my controller
public function getAbsen() {
$month = date('11');
$year = date('Y');
$id_karyawan = 26;
// $data = $this->m_data->rekapAbsen($id_karyawan, $month, $year);
$data = $this->m_data->rekapAbsenFullCalendar($id_karyawan);
foreach ($data as $val) {
$id = $val["id_attendance"];
$tgl_db = $val["date_log"];
$tgl = date('Y-m-d', strtotime($tgl_db));
$d = $val["days"];
$c = $val["check_in"];
$o = $val["check_out"];
if ($d == 'Saturday') {
$days = 'Day Off';
} if ($d == 'Sunday') {
$days = 'Day Off';
} else {
if ($c == '00:00:00') {
$days = 'Day Off';
} else {
$days = 'Work';
}
}
$data_array[] = array(
// 'id_attendance' => $id,
'title' => $days,
'start' => $tgl,
'end' => $tgl,
// 'allday' => '0'
);
}
// var_dump($data);
echo json_encode($data_array);
}
and this my fullcalendar, data not showing
where is the fault?
The docs show there are a few methods of specifying a JSON feed of events.
The simplest option is just:
events: '/myfeed.php'
Alternatively, you can use the extended form if you want to also specify some options:
eventSources: [
{
url: '/myfeed.php',
color: 'yellow',
textColor: 'black'
}
Your code does not use either of these formats - you have eventSources but without a url, and with events.
Update your code as follows:
eventSources: [{
color: '#306EFE',
textColor: '#ffffff',
url: "<?= base_url('UserDashboard/getAbsen'); ?>"
}]
The rest of your code works fine, here's a working jsFiddle.
My head is going to blow.
livedata.php loads json when page open.
live.php add point to graph.
From livedata.php i got output like this:
[["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37],["Date.UTC(2016, 07-1, 28, 15, 08)",37]]
live.php output - only last row, looks like
["Date.UTC('.2016, 07-1, 29, 15, 40.')", 44]
I've got chart, live addPoint working, but no date on x-axis. What i do wrong?
JS
var chart;
function requestData() {
$.ajax({
url: 'live.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 120; // shift if the series is
chart.series[0].addPoint(eval(point));
setTimeout(requestData, 10000);
},
cache: false
});
}
$(function () {
$.ajax({
url: 'livedata.php',
success: function(point) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'areaspline',
events: {
load: requestData
}
},
title: {
text: 'Revenue vs. Overhead',
},
subtitle: {
text: '',
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Amount'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
series: [{
name: 'Random data',
data: eval(point )
}]
});
},
});
});
live.php
global $dbConnection;
$stmt = $dbConnection->query('SELECT DATE_FORMAT(data,"%Y-%m-%d %H:%i") as dataa, humidity FROM sensorsdata order by id desc limit 1');
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$date_raw = strftime('%Y, %m-1, %d, %H, %M', strtotime($row[dataa]));
$date_complete = "Date.UTC('.$date_raw.')";
$ar = array($date_complete, $row[humidity]);
echo json_encode($ar, JSON_NUMERIC_CHECK);
livedata.php
global $dbConnection;
$stmt = $dbConnection->query('SELECT DATE_FORMAT(data,"%Y-%m-%d %H:%i") as dataa, humidity FROM sensorsdata');
$result = $stmt->fetchAll();
foreach ($result as $row) {
$date_raw = strftime('%Y, %m-1, %d, %H, %M', strtotime($row[dataa]));
$date_complete = 'Date.UTC('.$date_raw.')';
$hum_for_chart[] = [$date_complete, $row[humidity]];
}
echo json_encode($hum_for_chart, JSON_NUMERIC_CHECK);
Chart:
Chart
I think its problem of your data try to make string like,
live.php
....
$date_complete = "Date.UTC('.$date_raw.')";
$ar = "[".$date_complete.",". $row[humidity]."]";
echo json_encode($ar);
livedata.php
....
foreach ($result as $row) {
$date_raw = strftime('%Y, %m-1, %d, %H, %M', strtotime($row[dataa]));
$date_complete = 'Date.UTC('.$date_raw.')';
$hum_for_chart[] = "[".$date_complete.",". $row[humidity]."]";
}
....
You can refer highcharts-data-series-issue-with-ajax-json-and-php
i've got it! 2 days of mind blowing ))))
Thanks to Rohan Kumar for link.
I made changes from date.utc to unix timestamp.
$datetimeUTC = ((strtotime($row[dataa])+ 10800) * 1000);
$data[] = [$datetimeUTC, $row[humidity]];
echo json_encode($data);
10800 - that is +3 hours (Moscow timezone)
The output is
[[1469718529000,37],[1469718529000,37],[1469718530000,37],[1469718531000,37]]
And that's it, date axis started working!
Hi guys i need help with Highcharts library, i have this array coming from php,
[{"name":"25% en cambio de aceite 76 lubricants","data":[["2015-09-07",1],["2015-09-23",2],["2015-09-24",3],["2015-09-30",3]]},{"name":"10% Descuento en filtro de aceite","data":[["2015-09-07",1],["2015-09-23",2],["2015-09-24",3],["2015-09-30",3],["2015-10-03",3],["2015-10-05",1],["2015-10-09",1],["2015-10-10",1]]}]
I need to show this as line chart dynamically, but have been unable to do it, i believe the error comes from the quotes in dates, needs to be in format [Date.UTC(2015, 2, 6), 3]
This is my php function that returns the json data
public function actionTransactionsRedeemed() {
// Transacciones Totales redimidas por merchant
$sql = "SELECT DISTINCT `transaction`.idPromotion, promotion.`name` FROM `transaction` INNER JOIN promotion ON `transaction`.idPromotion = promotion.idPromotion WHERE `transaction`.idMerchant = 2 AND `transaction`.idPromotion IS NOT NULL";
$idPromotion = Yii::app()->db->createCommand($sql)->queryAll();
$idPromotions = array();
$tempArray = array();
$result = array();
$i = 1;
$rs = array();
foreach($idPromotion as $i){
//process each item here
$id = $i["idPromotion"];
$tempArray['name'] = $i["name"];
$sql = "SELECT count(*) AS count, DATE(`transaction`.date) AS `date` FROM `transaction` WHERE `transaction`.idMerchant = 2 AND `transaction`.idPromotion = $id GROUP BY DATE(`transaction`.date)";
$transactionsRedeemed = Yii::app()->db->createCommand($sql)->queryAll();
foreach($transactionsRedeemed as $item2){
$rs[0] = $item2['date'];
$rs[1] = $item2['count'];
$tempArray['data'][] = $rs;
$rs = array();
}
$i++;
array_push($result, $tempArray);
}
//$result = json_encode($result, JSON_NUMERIC_CHECK);
//echo json_decode($result);
print json_encode($result, JSON_NUMERIC_CHECK);
}
And this is the Jquery that builds the chart
$(document).ready(function() {
var options = {
chart: {
type: 'spline',
renderTo: 'chart-merchant-day',
defaultSeriesType: 'spline',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Total de promociones redimidas',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
},
labels: {
align: 'center',
x: -3,
y: 20,
formatter: function() {
return Highcharts.dateFormat('%l%p', this.value);
}
}
},
yAxis: {
title: {
text: 'Transacciones'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return Highcharts.dateFormat('%l%p', this.x-(24000*3600)) +'-'+ Highcharts.dateFormat('%l%p', this.x) +': <b>'+ this.y + '</b>';
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
name: 'Count'
}],
credits: false
}
// Load data asynchronously using jQuery. On success, add the data
// to the options and initiate the chart.
jQuery.get('?r=/transactions/transactionsRedeemed', null, function(tsv) {
var lines = [];
traffic = [];
var data = $.parseJSON(tsv);
var x = 0;
//console.log(tsv);
$.each(data, function(i, item) {
//alert(item);
//console.log(item);
$.each(item, function(y, item2) {
if(y == "data"){
//console.log(item2);
try {
tsv = item2;
// split the data return into lines and parse them
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
line = line.split(/\t/);
options.series[x].data.push([Date.parse(line[0]),line[1]]);
/*date = Date.parse(line[0] +' UTC');
traffic.push([
date,
parseInt(line[1].replace(',', ''), 10)
]);*/
});
} catch (e) { }
options.series[x].data = traffic;
} else if(y == "name"){
options.series[x].name = item2;
}
});
x++;
});
chart = new Highcharts.Chart(options);
//console.log(tsv.replace(/\"/g, ""));
//tsv = tsv.replace(/\"/g, "");
});
});
Any help will be greatly appreciated, im so exhausted at this point.
The function is actually simpler,
jQuery.get('?r=/transactions/transactionsRedeemed', null, function(tsv) {
var data = $.parseJSON(tsv);
$.each(data, function (i, item) {
options.series.push({
name: item['name'],
data: []
});
$.each(item['data'], function (j, dataitem) {
var dataitemvalue = null;
try {
dataitemvalue = [Date.parse(dataitem[0]), dataitem[1]];
} catch (e) {}
options.series[i].data.push(dataitemvalue);
});
});
chart = new Highcharts.Chart(options);
});
JSFiddle demo
I'm trying to convert the static data to using database results. I'll be using MySQL and PHP.
Example Code:
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var lineChartData = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
label: "My First dataset",
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
},
{
label: "My Second dataset",
fillColor : "rgba(151,187,205,0.2)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(151,187,205,1)",
data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
}
]
}
window.onload = function(){
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: true
});
}
Below is my php/msql:
$result = mysql_query("SELECT COUNT(*) FROM customer WHERE month='january'") or die(mysql_error());
$row1 = mysql_fetch_array( $result );
$result = mysql_query("SELECT COUNT(*) FROM customer WHERE month='february'") or die(mysql_error());
$row2 = mysql_fetch_array( $result );
$result = mysql_query("SELECT COUNT(*) FROM customer WHERE month='march'") or die(mysql_error());
$row3 = mysql_fetch_array( $result );
How could I use those count() from my MySQL query and implement it to datasets on chartjs? I would also like the labels to be generated from my MySQL query too. Should I loop the datasets inside the jQuery code?
This is the plugin that I'm using : http://www.chartjs.org/docs/#line-chart-introduction
First get your data into suitable data structures using PHP
$months = array("january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december");
$monthvalues = array();
foreach ($months as $month) {
$monthvalues[$month] = 0;
}
$result = mysql_query("SELECT month, count(*) FROM customer group by month") or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$monthvalues[$row[0]] = (int)$row[1];
}
Below that, just plug in those data structures into your Javascript
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var lineChartData = {
labels : <?=json_encode($months);?>,
datasets : [
{
label: "My First dataset",
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : <?=json_encode(array_values($monthvalues));?>
}
]
}
assuming the the window.onload and the HTML for the canvas element are in their proper places.
Please place your php code into another file called api.php and use $.ajax to get these data with JSON format. To convert data into JSON format data you should use json_encode() php function.
I have set sample example you can see here.
Please refer below code example:
api.php
$arrLabels = array("January","February","March","April","May","June","July");
$arrDatasets = array('label' => "My First dataset",'fillColor' => "rgba(220,220,220,0.2)", 'strokeColor' => "rgba(220,220,220,1)", 'pointColor' => "rgba(220,220,220,1)", 'pointStrokeColor' => "#fff", 'pointHighlightFill' => "#fff", 'pointHighlightStroke' => "rgba(220,220,220,1)", 'data' => array('28', '48', '40', '19', '86', '27', '90'));
$arrReturn = array(array('labels' => $arrLabels, 'datasets' => $arrDatasets));
print (json_encode($arrReturn));
example.html
$.ajax({
type: 'POST',
url: 'api.php',
success: function (data) {
lineChartData = data;//alert(JSON.stringify(data));
var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Line(lineChartData);
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {responsive: true});
}
});
Please note that you should pass value of randomScalingFactor() at api.php.
Please check and let me know if you require any further help.
This is based on the answer above with a couple of changes.
php:
include 'db.php';
$query = "SELECT month, COUNT(*) count FROM customer WHERE month='march' GROUP BY month";
if ($stmt = $conn->prepare($query)) {
$stmt->execute();
$stmt->bind_result($month, $count);
$labels = array();
$data = array();
while ($stmt->fetch()) {
$labels[] = $month;
$data[] = $count;
}
$stmt->close();
}
$datasets = array('label'=>"timer",'data'=> $data);
$data = array('labels'=>$labels, 'datasets'=> array($datasets));
echo json_encode($data);
I had to use JSON.pare() on the passed-in array.
Javascript:
$.ajax({
type: 'POST',
url: 'api.php ',
datatype: 'json',
success: function (result) {
var ctx = document.getElementById("chart").getContext("2d");
var mychart = new Chart(ctx,
{
type: 'bar',
data: JSON.parse(result),
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
})
}
})
html:
<canvas id="chart" width="200" height="200"></canvas>
I'm trying to retrieve results using json in order to display world map with country list.
This is what I got so far:
function drawRegionsMap() {
$.ajax({
url: 'getlist.php",
dataType: "json"
}).done(function(result) {
var data = google.visualization.arrayToDataTable(result);
var view = new google.visualization.DataView(data)
view.setColumns([0, 1])
var chart = new google.visualization.GeoChart(
document.getElementById('map'));
chart.draw(data, options);
var geochart = new google.visualization.GeoChart(
document.getElementById('map'));
var options = {
width: "auto",
height: "auto",
colorAxis: {
colors: ['#E4B6D3', '#E06D94']
} // Map Colors
};
geochart.draw(data, options);
});
};
google.load('visualization', '1', {
'packages': ['geochart']
});
google.setOnLoadCallback(drawRegionsMap);
result returned from getlist.php is in json format:
{
"Country":[
"Germany",
"United States",
"Brazil",
"France",
"RU"
],
"Hits":[
200,
300,
400,
500,
600,
700
]
}
php code:
$data = array();
$data['Country'] = array();
$data['Hits'] = array();
$country = array('Germany','United States','Brazil','France','RU');
$hits = array(200,300,400,500,600,700);
for ($i = 0; $i < 6; $i++){
$data['Country'] = $country;
$data['Hits'] = $hits;
}
echo json_encode($data);
Looking in firebug console, I'm always getting : Error: Not an array
I've been trying to solve this puzzle for hours, but no success.
The returned result is an object, not an array.
The expected array would be:
[
["Country","Hits"],
["Germany",200],
["United States",300],
["Brazil",400],
["France",500],
["RU",600]
]
Modified PHP-code that returns this array:
<?php
$data = array(['Country','Hits']);
$country = array('Germany','United States','Brazil','France','RU');
$hits = array(200,300,400,500,600,700);
foreach ($country as $k => $v){
$data[] = array($v,$hits[$k]);
}
echo json_encode($data);
?>