Mark date as booked in fullcalendar - php

I'm using http://arshaw.com/fullcalendar/ to display a full calendar to show events from a DB via json. I need to mark a date as booked by changing the color of the calender cell.
So im guessing I need something like
If (date == booked){
$(element).css("backgroundColor", "red");
}
Here is the code for populating the calendar.
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: false,
events: {
url: '{{URL::to('/json')}}',
type: 'GET',
},
'': 'h(:mm)t' ,// uppercase H for 24-hour clock
loading: function(bool) {
if (bool) $('#loading').show();
else $('#loading').hide();
}
});
});
Here is my json object
public function json()
{
$bookings = Booking::all();
//dd($bookings);
foreach ($bookings as $b)
$data[] = ['title'=>$b->status,
'start'=> $b->event_date .' ' .$b->start_time,
'end'=>$b->event_date .' ' .$b->end_time,
'description'=>'',
'color'=>'',
'status'=>$b->status,
'backgroundColor' => ($b->status ==='confirmed'?'#FFC0CB' : '#FFA500'),
'slotMinutes'=>'10',
'allDay'=>false];
//return $bookings;
return $data;
}
Ideally I'd like to send an array of dates I need to mark as booked.
If someone can nudge me in the correct direction I'd really appriciated it.
Thanks

this is how I solved it.
eventRender: function (event, element, monthView) {
if (event.title == "booked") {
var date = $.fullCalendar.formatDate( event.start , 'yyyy-MM-dd' );//event.start;
$('.fc-day[data-date="' + date + '"]').addClass('booked');
}
},

Related

Pass PHP values to Jquery Calendar

I am working on a JQuery event calendar that I would like to populate with multiple values from PHP. I've got a foreach pulling all PHP values needed, but I'm not sure how to properly populate the events array in JQuery with the values that I have PHP gathering.
Thanks in advance for any advice here.
Here is the PHP foreach that gathers all of the event data needed.
<?php foreach ($collection as $content) : ?>
<?php
$eventTitle = $content->getData('title');
$ogDate = $content -> render('mmedia_library_publish_date', array('type' => 'date_short'));
// REFORMAT DATES FROM PHP TO A CALENDAR FRIENDLY FORMAT
$newDate = date('Y-d-m', strtotime($ogDate));
echo $newDate;
?>
<?php endforeach; ?>
Here is the jQuery that populates the calendar, with some dummy events in-place, for reference on the formatting that is needed.
<script type="text/javascript">
require([
'jquery',
'calendar-gc',
'domReady!'
], function ($) {
require(['jquery'],function(e){
var calendar = $("#calendar").calendarGC({
dayBegin: 0,
prevIcon: '<',
nextIcon: '>',
onPrevMonth: function (e) {
console.log("prev");
console.log(e)
},
onNextMonth: function (e) {
console.log("next");
console.log(e)
},
// *********** ADD EVENTS FROM PHP HERE *************
events: [
{
date: new Date("2022-03-15"),
eventName: "EVENT 1",
className: "badge bg-danger",
onclick(e, data) {
console.log(data);
},
dateColor: "red"
},
{
date: new Date("2022-03-20"),
eventName: "EVENT 2",
className: "badge bg-danger",
onclick(e, data) {
console.log(data);
},
dateColor: "red"
},
{
date: new Date("2022-03-22"),
eventName: "EVENT 3",
className: "badge bg-success",
onclick(e, data) {
console.log(data);
},
dateColor: "green"
}
],
onclickDate: function (e, data) {
console.log(e, data);
}
});
})
});
</script>
Not that I recommend this approach but can you try something like
//...
$dateArr = [];
foreach () {
...
$dateArr[] = $newDate;
..
}
echo sprintf('<script>let eventStr = %s;</script>', implode(',', $dateArr));
and then later or at the end of page,
let cal = [];
let dates = eventStr.split(',');
dates.forEach(date => cal.push({
date: new Date(date),
eventName: "EVENT 2",
className: "badge bg-danger",
onclick(e, data) {
console.log(data);
},
dateColor: "red"
})
);
haven't tested it but something like this will make values available on the page and then when you initialize the calendar, you can use that array instead.
var calendar = $("#calendar").calendarGC({
...
...
events: cal,
...
});
Just wanted to post my solution to the original question. The comment/post from Adison Masih pointed me in the right direction (thank you), along with extensive searching, trial and error to get the array to display as needed in jquery.
Hopefully, this will help someone else out there that is looking to perform a similar task.
I ended-up building the array in PHP and format the date with the following code:
<?php $eventData = array(); ?>
<?php
$eventTitle = '<a class="eventCalTitle" href="'.$content->getLinkUrl().'">' .$content->getData('title'). '</a>';
$ogDate = $content -> render('mmedia_library_publish_date', array('type' => 'date_short'));
$newDate = date('Y-m-d', strtotime($ogDate));
$jDate = $newDate;
$tempArray = array("date" => $jDate, "eventName" => $eventTitle, "className" => "badge", "dateColor" => "#006fba");
array_push($eventData, $tempArray)
?>
After the PHP array is created, I then pass the array to jQuery, using json_encode, then further modifying the date objects, adding the new Date() function and then populating the events array with my custom event data:
const jsonData = <?php echo json_encode($eventData); ?>;
$.each(jsonData, function( i, obj ) {
var dateOrig = obj.date;
obj.date = new Date(dateOrig);
});
const option = {
dayBegin: 0,
};
option["events"] = jsonData;
$("#calendar").calendarGC(option)

AJAX data not posting using FullCalendar when trying to update

I have a calendar.php file which looks up "php/get-events" to display calendar events from the database (This currently works as expected). I am trying to use "php/calendarupdate" to then update the database with the new start/end times that have been dragged, but the data posting to this page always comes back as undefined, so it's not finding it for some reason.
"Calendar.php"
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
},
initialDate: '2021-03-18',
editable: true,
eventDrop: function(event, delta) {
start=moment(event.start).format('Y-MM-DD HH:mm:ss');
end=moment(event.end).format('Y-MM-DD HH:mm:ss');
$.ajax({
url: 'php/calendarupdate.php',
data: 'title=' + event.title + '&start='+ event.start +'&end=' + event.end + '&id=' + event.id ,
type: "POST",
success: function(json) {
alert("Updated Successfully");
}
});
},
navLinks: true, // can click day/week names to navigate views
dayMaxEvents: true, // allow "more" link when too many events
events: {
url: '/php/get-events.php',
failure: function() {
document.getElementById('script-warning').style.display = 'block'
}
},
loading: function(bool) {
document.getElementById('loading').style.display =
bool ? 'block' : 'none';
}
});
calendar.render();
});
</script>
The following is where I get the data which successfully displays events on the calendar.
"php/get-events.php"
$stmt = $pdo->prepare("Select id,task_name,start,end,notes,task_type,status from tasks where attendees like ".$attendees);
$stmt->execute();
//$stmt->debugDumpParams();
foreach ($stmt as $row){
$rawdata[] = array('id' => $row['id'], 'title'=> $row['task_name'], 'start'=> $row['start'], 'end'=> $row['end']);
}
$rawdata = json_encode($rawdata);
echo $rawdata;
The following is the update file, which it is getting into ok, but the echo's I try to display are all undefined.
/* Values received via ajax */
echo "id -".$_POST['id'];
echo "start -".$_POST['start'];
echo "end -".$_POST['end'];
// update the records
$stmt = $pdo->prepare('UPDATE tasks SET start=?, end=? WHERE id=?');
$stmt->execute($_POST['start'], $_POST['end'], $_POST['id']);
$stmt->debugDumpParams();
It may be something simple, but from the documentation I've read, I can't seem to figure out why my variables are not posting successfully. Thanks.
You have the wrong syntax for your eventDrop signature. See https://fullcalendar.io/docs/eventDrop
It should be
eventDrop: function(info) {
And then replace
event.start
and
event.end
with
info.event.start
and
info.event.end
This will get the information you need correctly from the data which fullCalendar supplies.

How to populate Jvector Map with countries from database?

(I am new to Javascript and jQuery..) I have a dashboard and I want to display a map that shows the countries where participants of a particular event are coming from. With this, I opted with Jvector Map. I am having a hard time displaying the countries in the map, coming from my database.
dashboard.js
var mapData = {};
$('#world-map').vectorMap({
map: 'world_mill_en',
backgroundColor: "transparent",
regionStyle: {
initial: {
fill: '#e4e4e4',
"fill-opacity": 0.9,
stroke: 'none',
"stroke-width": 0,
"stroke-opacity": 0
}
},
series: {
regions: [{
values: function() {
$.ajax({
url:"includes/sql/fetchcountries.php",
method:"GET",
data:mapData,
dataType:"json",
success: function(data){
mapData = data;
console.log(mapData);
}
})
},
scale: ["#1ab394", "#22d6b1"],
normalizeFunction: 'polynomial'
}]
},
});
fetch.php
<?php
require '../auth/dbh.inc.auth.php';
$id = $_SESSION['ntc_id'];
$stmt = $conn->prepare("SELECT DISTINCT(participants.p_country) FROM ntc_participants
INNER JOIN participants ON participants.p_id=ntc_participants.p_id_fk
WHERE ntc_participants.ntc_id_fk=?");
$data = array();
mysqli_stmt_bind_param($stmt, "i", $id);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows === 0);
if($row = $result->fetch_assoc()) {
$data[] = [
$row['p_country'] => 0 ]; //the value 0 is just a placeholder.. The jvector map feeds on this format: "US":298, "SA": 200
}
echo json_encode($data);
?>
Could anyone be gracious enough to walk me through all the wrong things I'm doing in my code? Appreciate all the help! :)
Ajax is asynchronous, so You are creating the map before the data has been downloaded.
Initialize the map with empty values for Your region:
$('#world-map').vectorMap({
...
values: {}
...
});
Then, whenever You need to show the data, set it dynamically:
$.get("includes/sql/fetchcountries.php", function(data) {
var mapObj = $("#world-map").vectorMap("get", "mapObject");
mapObj.series.regions[0].setValues(data);
});
During the ajax invocation and data download maybe You can show a spinner (please look at beforeSend inside the jQuery full ajax documentation: https://api.jquery.com/jquery.ajax/).
Here is the reference for setValues:
http://jvectormap.com/documentation/javascript-api/jvm-dataseries/
http://api.worldbank.org/v2/country/all/indicator/NY.GDP.PCAP.PP.CD?format=json&date=2018
This link will give you up-to-date stats for most common indicators via json - and then you can pluck whatever data that you like. I don't have all the code yet, as I am working on this today too.
This answers the question above whenever your database can also present JSON
document.addEventListener('DOMContentLoaded', () => {
console.log("loaded")
fetchCountryData()
})
function fetchCountryData () {
fetch('http://api.worldbank.org/v2/country/all/indicator/NY.GDP.PCAP.PP.CD?format=json&date=2018')
//
.then(resp => resp.json())
.then(data => {
let country.id = data[1]
let indicator.id = data[1]
create-GDP-Data(country.id,indicator.id)
})
}
function create-GDP-Data(country.id,indicator.id){
let gdpData = ?
}
$('#world-map-gdp').vectorMap({
map: 'world_mill',
series: {
regions: [{
values: gdpData,
scale: ['#C8EEFF', '#0071A4'],
normalizeFunction: 'polynomial'
}]
},
onRegionTipShow: function(e, el, code){
el.html(el.html()+' (GDP - '+gdpData[code]+')');
}
});

Search through FullCalendar

I am building a college timetable with FullCalendar, php and mysql.
Events are created when you click in the calendar field; you assign a name for the event, a professor and a room. The event is saved in an sql databse.
I would like to add a search bar which would search through the timetable; a user could search for either professor, room number, event name. The timetable would update as the user types and it would re-fetch the event with that room number/event name/professor name.
Anyone have any clue how to do this?
This is the code i am using for rendering events from the mysql:
$sql = "SELECT id, title, naem, mentor, start, end, color FROM events ";
$req = $bdd->prepare($sql);
$req->execute();
$events = $req->fetchAll();
...
...
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
height:595,
defaultView: 'agendaWeek',
minTime: "07:00:00",
maxTime: "16:00:00",
editable: true,
eventLimit: true,
selectable: true,
selectHelper: true,
firstDay:"1",
select: function(start, end) {
$('#ModalAdd #start').val(moment(start).format('YYYY-MM-DD HH:mm:ss'));
$('#ModalAdd #end').val(moment(end).format('YYYY-MM-DD HH:mm:ss'));
$('#ModalAdd').modal('show');
},
eventRender: function(event, element) {
element.bind('dblclick', function() {
$('#ModalEdit #id').val(event.id);
$('#ModalEdit #title').val(event.title);
$('#ModalEdit #naem').val(event.naem);
$('#ModalEdit #mentor').val(event.mentor);
$('#ModalEdit #color').val(event.color);
$('#ModalEdit').modal('show');
});
element.find('.fc-title').append("<br/>" + event.naem + "<br/>" + event.mentor);
},
eventDrop: function(event, delta, revertFunc) {
edit(event);
},
eventResize: function(event,dayDelta,minuteDelta,revertFunc) {
edit(event);
},
events: [
<?php foreach($events as $event):
$start = explode(" ", $event['start']);
$end = explode(" ", $event['end']);
if($start[1] == '00:00:00'){
$start = $start[0];
}else{
$start = $event['start'];
}
if($end[1] == '00:00:00'){
$end = $end[0];
}else{
$end = $event['end'];
}
?>
{
id: '<?php echo $event['id']; ?>',
title: '<?php echo $event['title']; ?>',
naem: '<?php echo $event['naem']; ?>',
mentor: '<?php echo $event['mentor']; ?>',
start: '<?php echo $start; ?>',
end: '<?php echo $end; ?>',
color: '<?php echo $event['color']; ?>',
},
<?php endforeach; ?>
]
});
function edit(event){
start = event.start.format('YYYY-MM-DD HH:mm:ss');
if(event.end){
end = event.end.format('YYYY-MM-DD HH:mm:ss');
}else{
end = start;
}
id = event.id;
Event = [];
Event[0] = id;
Event[1] = start;
Event[2] = end;
$.ajax({
url: 'editEventDate.php',
type: "POST",
data: {Event:Event},
success: function(rep) {
if(rep == 'OK'){
alert('Spremljeno!');
}else{
alert('Nešto zajebaje...');
}
}
});
}
});
</script>
An autocomplete plugin such as this will help with the UI part: https://jqueryui.com/autocomplete/
Using this your user can find the IDs of the people / rooms / event names involved and choose one from the list of possibilities. You will need an ajax call and an associated server endpoint which will search the database based on what the user types into the box and return any matching results.
Then in fullCalendar use this format for your event feed https://fullcalendar.io/docs/event_data/events_function/ so that you can pass the selected ID from the autocomplete to the server as an extra parameter when fetching events.
Next listen to the autocomplete's "select" event (http://api.jqueryui.com/autocomplete/#event-select) and when a value is chosen, call "refetchEvents" (https://fullcalendar.io/docs/event_data/refetchEvents/) on the fullCalendar. This will update your events list, restricting it by the specific person/room/event ID as well as the standard parameters (i.e. those being the current start/end dates of the visible view).

jQuery FullCalendar doesn't show events issue in FireFox 33.0

I'm trying to set up jQuery FullCalendar by providing data as json feed trough fullcalendar events function. So basically this is my js code:
var calendar = $('#calendar').fullCalendar({
editable: true,
firstDay: 1,
header: {
left: 'prev, next today',
center: 'title',
right: 'month, agendaWeek, agendaDay'
},
events:
{
url: 'events.php',
type: 'POST',
cache: false,
error: function() {
alert('ERROR');
},
color: 'blue'
}
});
And my code from events.php which pulls data from database and makes as JSON feed + converting date to ISO8601 date strings as sayd in documentation.
// Query that retrieves events
$q = "SELECT * FROM evenement ORDER by id";
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_assoc($r))
{
$s = new DateTime($row['start']);
$e = new DateTime($row['end']);
$row['start'] = $s->format(DATE_ISO8601);
$row['end'] = $e->format(DATE_ISO8601);
$json[] = $row;
}
echo json_encode($json);
In IE11 and Chrome it shows all the events in calendar what are made in DB, but in FireFox the calendar is empty.. And returned response JSON string is:
[
{"id":"7","title":"Rino","start":"2014-10-22T11:55:46+0300","end":"2014-10-22T11:55:46+0300","url":"nav","allDay":"false"},
{"id":"8","title":"Rin","start":"2014-10-22T13:01:45+0300","end":"2014-10-22T13:01:45+0300","url":"Hello","allDay":"false"},
{"id":"9","title":"Rino","start":"2014-10-23T10:06:22+0300","end":"2014-10-23T10:06:22+0300","url":"Hello","allDay":"false"},
{"id":"10","title":"a","start":"2014-10-23T09:42:04+0300","end":"2014-10-23T09:42:04+0300","url":"a","allDay":"false"},
{"id":"11","title":"1","start":"2014-10-23T09:41:55+0300","end":"2014-10-23T09:41:55+0300","url":"1","allDay":"false"},
{"id":"12","title":"sdas","start":"2014-10-23T10:06:14+0300","end":"2014-10-23T10:06:14+0300","url":"1","allDay":"false"},
{"id":"13","title":"Prju","start":"2014-10-16T00:00:00+0300","end":"2014-10-17T00:00:00+0300","url":"undefined","allDay":"false"}
]
What am I missing, why in the Firefox it doesn't show any event? I have also tried clearing cache etc.. but without any results..

Categories