how to display data from a database to display on full calendar? - php

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.

Related

Laravel: how to show data to create chart in JavaScript file?

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!!

Ajax datatable not properly working in Laravel

I am a stuck with a problem.
I am having an ajax Datatable where I need to load the data via ajax. When I implemented the code Datatable pagination and sorting is not working. No error is displayed in the console. Don't know what to do.
here is my code...........
Controller Function
public function ajaxdata(Request $request)
{
$merchants = \DB::table('merchantsummary')->lists('id');
$queryBuilder = OrderQueueModel::take($request->input('length'))
->skip($request->input('start'))->select('order_queue.qid','order_queue.qorder_no','order_queue.created_at','customer.first_name','customer.last_name','merchant_queue_order.created_at as merchant_order_time')
->join('customer','customer.id','=','order_queue.customerid')
->join('merchant_queue_order','order_queue.qid','=','merchant_queue_order.order_queue_id')
->groupBy('merchant_queue_order.order_queue_id');
$orders = $queryBuilder->get();
$data = array();
$i=1;
foreach($orders as $order):
$merchant = MerchantOrderQueueModel::select('merchantsummary.merchant_name','merchant_queue_order.order_queue_id')
->join('merchantsummary','merchantsummary.id','=','merchant_queue_order.merchant_id')
->WHERE('merchant_queue_order.order_queue_id',$order->qid)
->get();
$merchList = '';
foreach($merchant as $mer):
if($merchList!=''){
$merchList .= ', ';
}
$merchList .= $mer->merchant_name;
endforeach;
$data[] = [ $i,
$order->qorder_no,
ucfirst($order->first_name).ucfirst($order->last_name),
date('d-m-Y H:i A', strtotime($order->created_at)),
date('d-m-Y H:i A', strtotime($order->merchant_order_time)),
$this->dateDifference($order->merchant_order_time,$order->created_at),
$merchList,
'</i> View',
];
$i++;
endforeach;
$totaldata = OrderQueueModel::count();
$totalfiltered = $orders->count();
$json_data = array(
"draw" => intval( $_REQUEST['draw'] ),
"recordsTotal" => intval( $totaldata ),
"recordsFiltered" => intval( $totalfiltered ),
"data" => $data
);
echo json_encode($json_data);
}
TableAjax.js
var orderRecords = function () {
var grid = new Datatable();
grid.init({
src: $("#order_ajax"),
onSuccess: function (grid) {
// execute some code after table records loaded
},
onError: function (grid) {
// execute some code on network or other general error
},
onDataLoad: function(grid) {
// execute some code on ajax data load
},
loadingMessage: 'Loading...',
dataTable: { // here you can define a typical datatable settings from http://datatables.net/usage/options
// Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout
// setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/scripts/datatable.js).
// So when dropdowns used the scrollable div should be removed.
//"dom": "<'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'<'table-group-actions pull-right'>>r>t<'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'>>",
"bStateSave": true, // save datatable state(pagination, sort, etc) in cookie.
"lengthMenu": [
[5,10, 20, 50, 100],
[5,10, 20, 50, 100] // change per page values here
],
"pageLength": 5, // default record count per page
"serverSide": true,
"columnDefs":[
{ // set default column settings
'orderable': true, 'targets': [0] },
{ "searchable": true, "targets": [0] },
],
"ajax": {
"url": "order/data", // ajax source
},
"order": [
[1, "asc"]
]// set first column as a default sort by asc
}
});
// handle group actionsubmit button click
grid.getTableWrapper().on('click', '.table-group-action-submit', function (e) {
e.preventDefault();
var action = $(".table-group-action-input", grid.getTableWrapper());
if (action.val() != "" && grid.getSelectedRowsCount() > 0) {
grid.setAjaxParam("customActionType", "group_action");
grid.setAjaxParam("customActionName", action.val());
grid.setAjaxParam("id", grid.getSelectedRows());
grid.getDataTable().ajax.reload();
grid.clearAjaxParams();
} else if (action.val() == "") {
Metronic.alert({
type: 'danger',
icon: 'warning',
message: 'Please select an action',
container: grid.getTableWrapper(),
place: 'prepend'
});
} else if (grid.getSelectedRowsCount() === 0) {
Metronic.alert({
type: 'danger',
icon: 'warning',
message: 'No record selected',
container: grid.getTableWrapper(),
place: 'prepend'
});
}
});
}
Need Help !! Waiting for the response..
The easiest way to apply server side data-table is:
Jquery:
$(document).ready(function() {
$('#data_table').dataTable({
"sServerMethod": "POST",
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "get_data.php"
});
});
Php: get_data.php
$start = $_REQUEST['iDisplayStart']; // to handle pagination
$length = $_REQUEST['iDisplayLength']; // to handle pagination
$sSearch = $_REQUEST['sSearch']; // for searching
$col = $_REQUEST['iSortCol_0'];
$arr = array(0 => 'id', 1 => 'first_name', 2 => 'last_name', 3 => 'email');
$sort_by = $arr[$col];
$sort_type = $_REQUEST['sSortDir_0'];
$qry = "select id, first_name, last_name, email, position, office from datatables_demo where (first_name LIKE '%".$sSearch."%' or last_name LIKE '%".$sSearch."%' or email LIKE '%".$sSearch."%') ORDER BY ".$sort_by." ".$sort_type." LIMIT ".$start.", ".$length;
$res = mysql_query($qry);
while($row = mysql_fetch_assoc($res))
{
$data[] = $row;
}
$qry = "select count(id) as count from datatables_demo";
$res = mysql_query($qry);
while($row = mysql_fetch_assoc($res))
{
$iTotal = $row['count'];
}
$rec = array(
'iTotalRecords' => $iTotal,
'iTotalDisplayRecords' => $iTotal,
'aaData' => array()
);
$k=0;
if (isset($data) && is_array($data)) {
foreach ($data as $item) {
$rec['aaData'][$k] = array(
0 => $item['id'],
1 => '<span id="'.$item['id'].'" name="first_name" class="editable">'.$item['first_name'].'</span>',
2 => '<span id="'.$item['id'].'" name="last_name" class="editable">'.$item['last_name'].'</span>',
3 => '<span id="'.$item['id'].'" name="email" class="editable">'.$item['email'].'</span>',
4 => '<span id="'.$item['id'].'" name="position" class="editable">'.$item['position'].'</span>',
5 => '<span id="'.$item['id'].'" name="office" class="editable">'.$item['office'].'</span>'
);
$k++;
}
}
echo json_encode($rec);
Its a little bit tough to understand the code on first time, but it will render full functional server side data-table

Can't see data from MySQL into fullcalendar

EDIT
Is it possible to send the json data into this part:
$.each( res, function(key, row)(
{
events: [
{
title: 'All Day Event',
start: //from AJAX row['name'],
backgroundColor: "#f56954", //red
borderColor: "#f56954" //red
},
...
I am trying to add data from MysQL into fullcalendar.
Here is my fullcalendar script:
<script>
(function ($) {
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
eventLimit: true, // allow "more" link when too many events
events: {
url: 'fullcalendar/get-events.php',
//url: 'fullcalendar/myfeed.php',
error: function() {
$('#script-warning').show();
}
},
loading: function(bool) {
$('#loading').toggle(bool);
}
});
});
})(jQuery);
</script>
Where I get values from get-events.php, and here is the code:
<?php
//Set error reporting on
error_reporting(E_ALL);
ini_set("display_errors", 1);
//Include connection file
require_once('global.php');
//Json and PHP header
header('Content-Type: application/json');
$events = array();
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
$search_date = "SELECT * FROM appointment WHERE id_logged = :id_logged";
$search_date_stmt = $conn->prepare($search_date);
$search_date_stmt->bindValue(':id_logged', $id_logged);
$search_date_stmt->execute();
$search_date_stmt_fetch = $search_date_stmt->fetchAll();
$search_date_stmt_count = $search_date_stmt->rowCount();
$i = 0;
foreach($search_date_stmt_fetch as $row)
{
$events[$i] = $row;
$i++;
}
echo json_encode($events);
?>
The result is show properly at the XHR:
But I can't see any of them in the calendar:
Build your response like the doc said :
$search_date_stmt_fetch = $search_date_stmt->fetchAll();
$search_date_stmt_count = $search_date_stmt->rowCount();
foreach($search_date_stmt_fetch as $row)
{
$events[] = array(
'start' => $row->your_date_start,
'end' => $row->your_date_end,
'id' => $row->your_id
...);
}
echo json_encode($events);
See the doc to know the properties you need : http://fullcalendar.io/docs/event_data/Event_Object/

How to add events in FullCalendar using an array retrieved from a mysql server (phpmyAdmin)?

I am grateful in advance of any help I receive on this. I also apologise if my error is obvious. My problem is I can't seem to find an idea on how to display all the elements of my array to populate my events.
for(var i = 0;i < count;i++)
{
// these are the arrays that contain my events
var primaryAsset = primaryAssets[i];
var release_Date = releaseDates[i];
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
weekMode: 'liquid',
weekends: true,
events: [
{
title: primaryAsset,
start: release_Date,
end: release_Date
}
]
});
}
Please create event array first then pass into full calender like
var evt = [
{
title : 'event1',
start : '2014-01-01'
},
{
title : 'event2',
start : '2014-01-05',
end : '2014-01-07'
},
{
title : 'event3',
start : '2014-01-09T12:30:00',
allDay : false
}
];
then add into full calender
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
weekMode: 'liquid',
weekends: true,
events: evt
});
This my script to get json data from php file. thats may works for you.
<script>
$('#calendar').fullCalendar(
{
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
events:
{ // Render the events in the calendar
url: 'calendarData.php', // Get the URL of the json feed
error: function()
{
alert('There Was An Error While Fetching Events Or The Events Are Not Found!');
}
}
});
</script>
calendarData.php
$return_array = array();
while ($row = mysql_fetch_array($sth))
{
$event_array = array();
$event_array['id'] = $row['e_id'];
$date_start = $row['e_date_start'];
$date_end = $row['e_date_end'];
$date_start = explode(" ",$date_start);
$date_end = explode(" ", $date_end);
$date_start[0] = str_replace('-' , '/' , trim($date_start[0]));
$date_end[0] = str_replace('-' , '/' , trim($date_end[0]));
//Event Title Structure
if($row['e_title'] != "")
{
$event_array['title'] = $row['e_title'];
//Start Date Structure
if($date_start[0] != "0000/00/00" && $date_start[1] != "00:00:00")
{
$event_array['start'] = date(DATE_ISO8601, strtotime($date_start[0]." ".$date_start[1]));
}
//End Date Structure
if($date_end[0] != "0000/00/00" && $date_end[1] != "00:00:00")
{
$event_array['end'] = date(DATE_ISO8601, strtotime($date_end[0]." ".$date_end[1]));
}
//All Day Event Structure
if($row['e_allday'] == '1')
{
$event_array['allDay'] = true;
}
elseif($row['e_allday'] == '0')
{
$event_array['allDay'] = false;
}
array_push($return_array, $event_array);
}
}
echo json_encode($return_array);
Here are the steps that I took, which worked pretty slick:
1. Load the calendar, using the basic code in fullCalendar documentation:
<script>
$(document).ready(function() {
// page is now ready, initialize the calendar...
$('#calendar').fullCalendar({
// put your options and callbacks here
})
});
</script>
make sure you can actually pull in the data from your array (it doesn't need to be in the calendar yet, just load it onto the page to verify that it works). Something like this should do it: (note, I have not tested this code, but it is close. May need to be tweeked though)
if ( have_posts() ) :
//start a while statement
while ( have_posts() ) :
the_post();
$content_types = get_the_terms( $post_id, $taxonomy_categories );
$tag_link = get_field('tag_link');
$tag_host = parse_url($tag_link);
$tag_page = $tag_host['scheme'] . '://' . $tag_host['host'];
echo the_title();
echo the_field('date');
endwhile;
endif;
add static array, to test if the array elements will be displayed on the calendar. Use code from fullCalendar documentation:
$('#calendar').fullCalendar({
events: [
{
title : 'event1',
start : '2010-01-01'
},
{
title : 'event2',
start : '2010-01-05',
end : '2010-01-07'
},
{
title : 'event3',
start : '2010-01-09T12:30:00',
allDay : false // will make the time show
}
]
});
Finally, once everything to this point is working, replace the static data with dynamic data. You can do this by wrapping it with a loop, and getting the necessary fields through php. Here is the code that I used:
<script>
$(document).ready(function() {
// page is now ready, initialize the calendar...
$('#calendar').fullCalendar({
// put your options and callbacks here
events: [
//start if
<?php
if ( have_posts() ) :
//start a while statement
while ( have_posts() ) :
the_post();
$content_types = get_the_terms( $post_id, $taxonomy_categories );
$tag_link = get_field('tag_link');
$tag_host = parse_url($tag_link);
$tag_page = $tag_host['scheme'] . '://' . $tag_host['host'];
?>
{
title : '<?php the_title();?>',
start : '<?php the_field('date');?>'
//only need one item in the array, because with the while loop, this will repeat until all the posts are added.
},
<?php
endwhile;
endif;
?>
]
})
});

Highchards - data loading from dbase

I'm looking for a help with loading data from dbase into Higtcharts.
The Highcharts data loading entrance looks like:
<script type="text/javascript">
jQuery(function() {
// Create the chart
window.chart = new Highcharts.StockChart({
chart: {
renderTo: 'container'
},
rangeSelector: {
selected: 1
},
title: {
text: 'USD to EUR exchange rate'
},
xAxis: {
maxZoom: 14 * 24 * 3600000 // fourteen days
},
yAxis: {
title: {
text: 'Exchange rate'
}
},
series: [{
name: 'USD to EUR',
data: usdeur
}]
});
});
</script>
and usdeur is loading as in scheme (example from external csv file):
var usdeur = [
[Date.UTC(2011,1,3),0.7488],
[Date.UTC(2011,2,6),0.6983],
[Date.UTC(2011,3,8),0.6961],
[Date.UTC(2011,4,9),0.6945]
];
from dbase SELECT I have:
$data_date = array();
$data_data = array();
foreach($STH as $row)
{
$date1 = $row['date'];
$date2 = explode("-", $date1);
$date3 = $date2[0].",".$date2[1].",".$date2[2];
$data_date[] = $date3; // date in scheme 2011,1,3
$data_data[] = $row['index_p_actual']; // data like 0.7488
}
info about date - $date_date[]
info about corelated data - $data_data[]
I want to load data online, not via any external file like csv.
And my question is - how to join $data_date and $data_data into one data pocket to receive completly virtual list like
[Date.UTC(2011,1,3),0.7488],
[Date.UTC(2011,2,6),0.6983],
[Date.UTC(2011,3,8),0.6961],
[Date.UTC(2011,4,9),0.6945]
The suggestion from highcharts is to use:
series: [{
data: [<?php echo join($data, ',') ?>]
}]
but I have $data & $date - how to join it? With php join I can use only one variable[] ...
Hmmm, or maybe another better way?
If I understood you well, I think you want to do this:
$data_date = array();
$data_data = array();
foreach($STH as $row)
{
$date1 = $row['date'];
$date2 = explode("-", $date1);
$date3 = $date2[0].",".$date2[1].",".$date2[2];
$data_date[] = $date3; // date in scheme 2011,1,3
$data_data[] = $row['index_p_actual']; // data like 0.7488
$data_highcharts[] = [$date3,$row['index_p_actual']]
}
And then you send the $data_highcharts[] to your JavaScript which will have the format:
[[date1,data1],[date2,data2],...]

Categories