DateTime conversion from FullCalendar to Controller PHP - javascript

I'm using FullCalendar to display a calendar on the web page (no surprise there).
A user can add events on the calendar, which is then passed through POST to the CodeIgniter controller. The controller executes a function in the model to insert the data in the database.
The problem I'm facing is that the date time, when inserted in the database adds 4 minutes for a reason i do not understand.
This is the JavaScript used for FullCalendar:
$(document).ready(function() {
var today = moment().day();
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
defaultView: 'agendaWeek',
eventLimit: true, // allow "more" link when too many events
selectable: true,
selectHelper: true,
select: function(start, end) {
var title = "<?=$anim['NOMANIM']?>";
var id = "<?=$anim['CODEANIM']?>";
if (title) {
start = moment(start).format('YYYY-MM-DD HH:mm:ss');
end = moment(end).format('YYYY-MM-DD HH:mm:ss');
$.ajax({
url: '<?php echo base_url("index.php/activite/add_activite"); ?>',
data: 'title='+ title+'&id='+ id+'&start='+ start +'&end='+ end,
type: "POST",
success: function(json) {
alert(start); // THIS SHOWS THE CORRECT DATETIME
}
})
};
$('#calendar').fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
}, true); // stick? = true
$('#calendar').fullCalendar('unselect');
},
events: <?=$events?>
});
});
And here is the controller function:
public function add_activite() {
$title = $_POST['title'];
$id = $_POST['id'];
$datetime_start = strtotime($_POST['start']);
$datetime_end = strtotime($_POST['end']);
$date = date('Y-m-d', $datetime_start);
$start = date('H:m:s', $datetime_start);
$end = date('H:m:s', $datetime_end);
$this->EZ_query->insert_activite($date, $start, $end);
}
If you think there is something I'm doing not correctly beside the time problem, I'm open to any pointers :), Thanks!

Your data formatting in php is not correct, minutes are denoted by i not m (which is used my month already). See here: http://php.net/manual/en/function.date.php
So change:
$start = date('H:i:s', $datetime_start);
$end = date('H:i:s', $datetime_end);

Related

Using php array in fullCalendar

I used the latest javascript fullCalendar (https://fullcalendar.io/) on a wordpress webpage to be able to display appointments of a wordress my users. So far the Callendar shows up on the page. Now I want to get the appointments from the db and display them in the Calendar.
If I create an array in php, with the appointments to display as a string, the appoinment shows up in the calendar.
Example:
$events = $wpdb->get_results("SELECT * FROM wp_projekt_calendar WHERE calendar_author=$uid");
foreach($events AS $event){
$array['title']= 'rtrt';
$array['start']= '2020-08-10 10:00:00';
$array['end'] = '2020-08-10 11:00:00';
}
echo json_encode($array);
But if I use the query results to show the appointment it doesent work (query works well!):
foreach($events AS $event){
$array['title']= $event_array->calendar_title;
$array['start']= $event_array->calendar_startdate .' '.$event_array->calendar_starttime;
$array['end'] = $event_array->calendar_enddate .' '.$event_array->calendar_endtime;;
}
echo json_encode($array);
This is how my calendar looks like:
<script>
document.addEventListener('DOMContentLoaded', function() {
var initialLocaleCode = 'de';
var localeSelectorEl = document.getElementById('locale-selector');
var calendarEl = document.getElementById('calendar');
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = new FullCalendar.Calendar(calendarEl, {
height: '100%',
expandRows: true,
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
},
initialView: 'dayGridMonth',
locale: initialLocaleCode,
navLinks: true, // can click day/week names to navigate views
editable: true,
selectable: true,
nowIndicator: true,
dayMaxEvents: true, // allow "more" link when too many events
events: {
url: "https://mydomainxy.com/wp-content/themes/gambit-child/events.php?uid='<?php // $anwender_id ?>'",
//url: "https://mydomainxy.com/wp-content/themes/gambit-child/php/get-events.php'",
type: 'POST',
error: function() {
alert('There was an error while fetching events.');
}
}
});
calendar.render();
});
</script>
What am I doing wrong or how can I get this to work?

Formatting fullcalendar js' date display on listMonth view

I'm currently converting a PSD design that requires the calendar to only display the event day, instead of displaying the full date. e.g. : 12 instead of October 12, 2016
Here's what I have so far:
As you can see on the left, it displays October 12, 2016. I want it to only display "12". I've tried looking at the docs but I can't find options specific for listMonth view. And here's my code for the calendar rendering:
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,listYear',
},
views: {
listMonth: {
titleFormat: 'MMMM'
}
},
defaultView: 'listMonth',
displayEventTime: false, // don't show the time column in list view
// THIS KEY WON'T WORK IN PRODUCTION!!!
// To make your own Google API key, follow the directions here:
// http://fullcalendar.io/docs/google_calendar/
//googleCalendarApiKey: 'AIzaSyDcnW6WejpTOCffshGDDb4neIrXVUA1EAE',
// US Holidays
//events: 'en.usa#holiday#group.v.calendar.google.com',
events: [
<?php if( $events->have_posts() ) :
while ($events->have_posts()) : $events->the_post();
$event_dates = get_post_meta(get_the_id(), 'date', true);
$event_info = get_post_meta(get_the_id(), 'info', true);
//foreach($event_dates as $event_date):
?>
{
title: '<?php the_title(); ?>',
start: '<?php echo date('Y-m-d', strtotime($event_dates["start_date_time"])); ?>',
description: '<?php echo date('ga', strtotime($event_dates["start_date_time"])).', '.$event_info["venue"].', '.$event_info["place"]; ?>'
},
<?php endwhile; ?>
<?php endif; ?>
// more events here
],
eventRender: function(event, element, view) {
return $('<tr><td>' + event.description + '</td></tr>');
},
eventClick: function(event) {
// opens events in a popup window
window.open(event.url, 'gcalevent', 'width=700,height=600');
return false;
},
loading: function(bool) {
$('#loading').toggle(bool);
}
});
});
</script>
I hope someone can help me out with this one. That's all I need and then I'm done. Thanks!
just use this :
$(".fc-list-heading-alt").html($(".fc-list-heading-alt").text().split(" ")[1].split(",")[0]);
after calendar is rendered. Hope, this will help you
and also add this onclick in next, prev buttons

Display date from database using jquery fullcalendar

I'm using the jquery fullcalendar plugin. I can display dynamic dates on a button click. The issue I have now is when loading the dates from the db all the dates populate just one day.
Here is the code with the call to the web service:
$('#calendar').fullCalendar({
header: {
left: 'prev, next today',
center: 'title',
right: 'month, agendaWeek, agendaDay'
},
defaultView: 'month',
editable: true,
allDaySlot: false,
selectable: true,
slotMinutes: 15,
events: 'DAL/WebService1.asmx/GetEvents',
allDay:false
});
Here is the date from that web method
$('#calendar').fullcalendar('renderEvent',event_object,'stick')
This will attach your event to its date on the calendar. The event_object only needs a title and a start date to be valid, but I'd suggest adding an id to make editing/deleting easier.
Render event documentation
Figured out how to get the calendar to render dates separately with this code here. Hopefully helps somebody in the future
var events = [];
$('#calendar').fullCalendar({
events: function (start, end, timezone,callback) {
$.ajax({
url: 'DAL/WebService1.asmx/GetEvents',
dataType: 'json',
success: function (data) {
console.log(data);
var events = [];
$(data).each(function (index, d) {
events.push({
title: d.title,
start: d.startDate
});
});
callback(events);
}
});
}
});

How can i read events from my database table and show them in their respective dates in java script and jquery

i use Full calendar plugin to do this and i have done something but still did not get up to mark.
hear is my scripting code
$('#calendar').fullCalendar({
//theme: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
buttonText: {//This is to add icons to the visible buttons
prev: "<span class='fa fa-caret-left'></span>",
next: "<span class='fa fa-caret-right'></span>",
today: 'today',
month: 'month',
week: 'week',
day: 'day'
},
editable: true,
droppable: true, // this allows things to be dropped onto the calendar
drop: function(date) { // this function is called when something is dropped
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
copiedEventObject.backgroundColor = $(this).css("background-color");
copiedEventObject.borderColor = $(this).css("border-color");
console.log(copiedEventObject);
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// is the "remove after drop" checkbox checked?
/*alert(date + ' was moved ' + allDay + ' days\n' +
'(should probably update your database)');*/
},
//events:"web_master/mycal/ajax_fetch_calendar_data",
events: function(start, end, timezone, callback) {
$.ajax({
url: 'web_master/mycal/ajax_fetch_calendar_data',
dataType: 'json',
type: "POST",
success: function(doc) {
//console.log(doc);
var events = [];
$(doc).find('event').each(function(){
console.log(doc);
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
});
}
});
},
});
in this i successfully found my doc in events section.
here is the code to fetch events from DB
public function ajax_fetch_calendar_data()
{
try
{
$info = $this->mod_rect->fetch_calendar();
#pr($info);
for($i = 0 ; $i < count($info) ; $i++)
{
$rows[]= array("id"=>$info[$i]['i_id'],
"title"=> $info[$i]['s_title'],
"start"=> $info[$i]['dt_start_date'],
"end"=>$info[$i]['dt_end_date'],
"allDay"=> $info[$i]['s_allDay']);
}
if($rows)
{
echo json_encode($rows);
}
}
catch(Exception $err_obj)
{
show_error($err_obj->getMessage());
}
}
but there is an find(event) function which is didn't found.
Basically what i need to do that
i have some events, those are fetch from DB and i have to drag them on the specific date on the date that comes(upto this done), but i want to store that in Db and fetch them from DB.
I am new to java script and jquery and i didn't know about JSON also.
any help regarding this will helpfull to me.
Thanks.
Well
After few days I have done it myself.
And I think it would be help full to someone So i update my Question
In the Events Section of Fullcalendar for reading multiple events and showing them in your Fullcalendar
events: function(start, end, callback) {
$.ajax({
url: 'web_master/mycal/ajax_fetch_calendar_data',
dataType: 'json',
type: "POST",
success: function(doc) {
var eventObject = [];
for(i=0;i<doc.length;i++)
{
eventObject.push({
id : doc[i].id,
start : doc[i].start,
end : doc[i].end,
title : doc[i].title
//allDay : doc[i].allDay,
//backgroundColor : doc[i].backgroundColor,
//borderColor : doc[i].borderColor
});
}
callback(eventObject);
}
});
},
And i fetch it from my DB in this way
public function ajax_fetch_calendar_data()
{
try
{
$info = $this->mod_rect->fetch_calendar();
echo json_encode($info);
}
catch(Exception $err_obj)
{
show_error($err_obj->getMessage());
}
}

Django Javascript Explanation

I have this code and I'm trying to make sense of it - I'm not really sure how it works-
{% if book %}
<script type='text/javascript'>
$(document).ready(function() {
$.get('/ajax/book/{{ book.id }}/timetable/', {}, function(data) {
data = JSON.parse(data);
var events = new Array();
for (var i in data) {
events.push({
id: data[i].id,
title: '{{ request.user.name }}',
start: Date.parse(data[i].startTime, "yyyy-MM-dd HH:mm:ss"),
end: Date.parse(data[i].endTime, "yyyy-MM-dd HH:mm:ss"),
allDay: false
});
}
var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'agendaDay,agendaWeek'
},
theme: true,
contentHeight: 400,
defaultView: 'agendaWeek',
selectable: true,
selectHelper: true,
eventClick: function(calEvent, jsEvent, view) {
},
select: function(start, end, allDay) {
var title = '{{ request.user.name }}';
$.post('/ajax/book/{{ book.id }}/timetable/new/', {
csrfmiddlewaretoken: getCookie('csrftoken'),
startTime: start.format("yyyy-mm-dd HH:MM:ss"),
endTime: end.format("yyyy-mm-dd HH:MM:ss"),
}, function(data) {
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true // make the event "stick"
);
});
calendar.fullCalendar('unselect');
},
editable: true,
events: events,
eventResize: function(event, dayDelta, minuteDelta, revertFunc) {
alert(
"The end date of " + event.title + " has been moved " +
dayDelta + " days and " +
minuteDelta + " minutes."
);
if (!confirm("Is this okay?")) {
revertFunc();
}
}
});
});
});
</script>
From what I can tell, ajax/book/.../timetable and ajax/book/.../timetable/new call book_timetable(request,id) and book_timetable_new(request,id)-
url(r'^ajax/book/(?P<bookid>\d+)/timetable/$', twobooks.ajax.views.book_timetable),
url(r'^ajax/book/(?P<bookid>\d+)/timetable/new/$', twobooks.ajax.views.book_timetable_new),
where the functions are -
def book_timetable(request, bookid):
book = get_object_or_404(Book, id=bookid)
rawslots = TimeSlot.objects.filter(user=request.user).filter(book=book)
slots = []
for rawslot in rawslots:
slot = {
'id': rawslot.id,
'startTime': str(rawslot.startTime),
'endTime': str(rawslot.endTime),
}
slots.append(slot)
return HttpResponse(simplejson.dumps(slots))
def book_timetable_new(request, bookid):
book = get_object_or_404(Book, id=bookid)
startTime = datetime.strptime(request.POST['startTime'], "%Y-%m-%d %H:%M:%S")
endTime = datetime.strptime(request.POST['endTime'], "%Y-%m-%d %H:%M:%S")
timeslot = TimeSlot(
user = request.user,
book = book,
startTime = startTime,
endTime = endTime,
)
timeslot.save()
return JSONify("")
I'm trying to do something similar to this, except with other data, which is why I'm trying to get how this works. If anyone could explain it to me it'd be great!
This is a fairly standard AJAX pattern. The template is rendered by the original view, as normal. In the course of rendering, some elements of the Javascript which are marked as Django template variables are filled in - eg {{ book.id }} and {{ request.user.name }} - so that by the time it gets to the browser, those are indistinguishable from the rest of the JS.
Now, the Javascript makes a call to the server, passing those elements. The server responds with JSON data, which is parsed by the function which is the third parameter to the .get call. I haven't looked too deeply into that function, but it seems to be using that data to instantiate a fullCalendar, which is presumably a separate jQuery script.
One slightly strange thing is that the AJAX call is set to run as soon as the browser has loaded the page - normally there's no point doing that, since you could simply include the data in the original template. Usually AJAX is set to execute in response to some event in the browser, such as a button click.

Categories

Resources