full calendar event drop is not working - javascript

I am making the reservation website by using full calendar. I want to change the date that user booked by dragging the event to other place. However, the drag is worked, but drop is not working. When I drop the event, then the event just disappear, and when I reload the page, then it appear where it used to be.
Here is code for javascript
$(function() { // document ready
var originalDate;
$('#calendar').fullCalendar({
eventDragStart: function(event) {
originalDate = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm"); // Make a copy of the event date
},
eventDrop:function(event)
{
var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm");
//get new Date
var id = event.id; //get userID who booked this event
$.ajax({
url:"http://show981111.cafe24.com/login-system/update.php",
type:"POST",
data:{newlyBookedDate: start, userID: id, oldDate: originalDate}, // send data
success:function()
{
console.log(response);
$("#calendar").fullCalendar('refetchEvents');
alert("Date has changed.");
location.reload();
}
});
},
Here is code for update.php.
What I am trying to do here is get the changed Date, and update the newly booked Date,which had the old Date, to newly booked Date, which is changed Date when I get from eventDrop.
<?php
$connect = new PDO('mysql:host=localhost;dbname=show981111', 'show981111', 'pass');
if(isset($_POST["newlyBookedDate"]))
{
$query = "UPDATE DAYSCHEDULE SET newlyBookedDate = :newlyBookedDate WHERE userID = :userID AND newlyBookedDate = :oldDate ";
$statement = $connect->prepare($query);
$statement->execute(
array(
':newlyBookedDate' => $_POST['newlyBookedDate'],
':userID' => $_POST['userID'],
':oldDate' => $_POST['oldDate']
));
}
?>
I checked console, and have this error:
fullcalendar.min.js:10 Uncaught TypeError: Cannot read property 'start' of undefined
at function.e.constructor.buildNewDateProfile (fullcalendar.min.js:10)
at function.e.constructor.mutateSingle (fullcalendar.min.js:10)
at function.e.constructor.R.internalApiVersion.f.mutateSingle (scheduler.min.js:6)
at fullcalendar.min.js:10
at Array.forEach (<anonymous>)
at constructor.mutateEventsWithId (fullcalendar.min.js:10)
at reportEventDrop (fullcalendar.min.js:9)
at fullcalendar.min.js:7
at i (fullcalendar.min.js:7)
at constructor.stop (fullcalendar.min.js:7)

Related

Auto Update div when new row is present on database

I am trying to retrieve all rows that are present within a table before the time the person has visited the page and there after update the div with any rows of data that has been added to the table since the user has been on the page.(Something like Whatsapp where the entire convo is visible and new messages get added to the bottom).
This is what I have so far using Ajax but I have no clue where I am going forward from this stage. It currently brings up only the newest record (IF I SET THE TIMESTAMP MANUALLY IN THE SECOND FILE) but not all the other records before it. Ideally I should work by posting the time to the second file.
How could I modify my code to get the functionality I desire?
Display (autoload.php)
var time = (new Date).getTime();
var interval = 1000; // 1000 = 1 second, 3000 = 3 seconds
function doAjax() {
$.ajax({
type: 'POST',
url: 'autoload2.php',
dataType: 'json',
data: 'time='+time,
success: function (data) {
$('.inner').append(data);
},
complete: function (data) {
setTimeout(doAjax, interval);
}
});
}
setTimeout(doAjax, interval);
Get data (autoload2.php)
$time = $_POST['time'];
$results = mysql_query("SELECT post_name FROM posts WHERE postime > $time limit 1");
$row = mysql_fetch_assoc($results);
$res = $row['post_name'];
echo json_encode($res);
Note: The time being used to query above doesn't work, only when it is hardcoded with the timestamp.
I think you need to move
var time = (new Date).getTime();
to your function
Because your time variable not changed
var interval = 1000; // 1000 = 1 second, 3000 = 3 seconds
function doAjax() {
var time = (new Date).getTime();
$.ajax({
type: 'POST',
url: 'autoload2.php',
dataType: 'json',
data: 'time='+time
}).done(function(response){
console.log(response);
});
}
setInterval(doAjax, interval);
In php:
$data = Array('name' => 'name of last row');
header('Content-Type: application/json');
echo json_encode($data);

Javascript error when trying to create a calendar

I'm brand new to javascript and php and having a slight problem.
I'm trying to create a php calendar that interacts with mysql database and have been trying to write some javascript to add events to the calendar.
My events are being brought from the mysql database but whenever I click to add an event to the calendar I get an error in the console saying "uncaught TypeError: undefined is not a function" which appears to be caused by these lines in the code:
var start = $.fullCalendar.formatDate(start, "yyyy-MM-dd HH:mm:ss");
var end = $.fullCalendar.formatDate(end, "yyyy-MM-dd HH:mm:ss");
My code is below, console log 'testing function success' is not being displayed. Please help!
$(document).ready(function() {
//get current date
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
theme:true,
weekNumbers: true,
//allow a 'more' option if too many events.
eventLimit: true,
//enables agenda view
header:{
left:'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
events: 'event.php',
selectable: true,
selectHelper: true,
select: function(start, end, allDay) {
console.log('testing function 1');
var title = prompt('Event Title:');
if (title) {
var start = $.fullCalendar.formatDate(start, "yyyy-MM-dd HH:mm:ss");
var end = $.fullCalendar.formatDate(end, "yyyy-MM-dd HH:mm:ss");
$.ajax({
url: 'eventadd.php',
data: 'title='+ title+'&start='+ start +'&end='+ end ,
type: "POST",
success: function(json) {
console.log('testing function success');
alert('OK');
}
});
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true // make the event "stick"
);
}
calendar.fullCalendar('unselect');
},
});
});
Instead of lines
var start = $.fullCalendar.formatDate(start, "yyyy-MM-dd HH:mm:ss");
var end = $.fullCalendar.formatDate(end, "yyyy-MM-dd HH:mm:ss");
use (take care not to redefine local varialbes start, end, which are params of the function, also use Moment's format function according to: http://momentjs.com/docs/#/displaying/format/ as recommended by the fullCalendar v2 code migration):
var sfmated = start.format("yyyy-MM-dd HH:mm:ss");
var efmated = end.format("yyyy-MM-dd HH:mm:ss");
a working jsfiddle is here:
http://jsfiddle.net/xv5n1wod/12/

How to Reload JSON data in Fullcalendar?

I am using Fullcalendar.
In my case I am adding Custom Events, Like when user clicks on specific date, he can add his event, when he is done with insertion, the custom event he just added show automatically appear on calendar, means the fresh JSON Data should reload and appear.
Here is my code:
events : "ajax/response.php",//Fetching JSON From PHP File//
function insertEventSchedule()
{
var title = $('#titl').val();
var fromDate = $('#fromDate').val();
var toDate = $('#toDate').val();
$.ajax({
type: "POST",
url : "ajax/insert_schedule_event.php",
data: "title="+title+"&fromDate="+fromDate+"&toDate="+toDate+"&timeStamp="+$.now(),
cache: false,
beforeSend: function()
{
$('.submit_data').html('<img src="include/content/loaders/ajax-loader.gif" width="20">');
},
success: function(html)
{
$('#myPopup').dialog('close');
}
});
}
}
You have to build an event Object and render that event using the renderEvent method before or after closing your dialog
UPDATE
var newEvent = new Object();
newEvent.title = "some text";
newEvent.start = new Date();
newEvent.allDay = false;
// ...
$('#calendar').fullCalendar( 'renderEvent', newEvent );
The complete list of event attribute are here

AJAX Adding Multiple Events Resetting Id Before Insert

In Full Calendar, i have some droppable external items. When i drag and drop one of them and immediately i delete it, it gets deleted, everything works fine. However, when i drop multiple items, such as 2 and when i delete 2 of them, both gets removed from calendar in the view, actually one gets removed from database, if i refresh the page i can see that.
When i check the form input hidden's value which is event's id fetched from database or returned from database as last insert id via ajax, both are the same it seems, actually they are not the same.
I think what i need is, resetting the eventID variable after they got dragged and dropped. I tried to initiliza them as empty, but it doesn't work.
How can i reset their values after ajax submit for the next units, hence keeping that variable to attached to current. Also its a global variable, i think this is the problem.
My Codes:
var eventID; // global variable
Drop Function:
drop: function(date, allDay) {
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;
if($extraEventClass) copiedEventObject['className'] = [$extraEventClass];
var tempDate = new Date(date);
copiedEventObject.start = $.fullCalendar.formatDate(copiedEventObject.start, "yyyy-MM-dd HH:mm:ss");
eventID = '';
$.ajax({
url: '<?=site_url("admin/calendar/add");?>',
data: 'title='+ copiedEventObject.title,
type: "POST",
success: function(newID){
eventID = newID;
//copiedEventObject._id = newID;
}
});
calendar.fullCalendar('renderEvent',
{
title: copiedEventObject.title,
start: date,
//id: copiedEventObject._id,
id: eventID,
}),
true // make the event "stick"
}
Event Click Function:
eventClick: function(calEvent, jsEvent, view) {
if(!eventID){
eventID = calEvent._id;
}
var form = $("<form id='changeName'>" +
"<h3 class='eventHeader'>Edit</h3>" +
"</div></form>");
form.append("<div class='controls'>" +
"<label class='control-label' for='title'>Name: </label>" +
"<input class='span3' name='title' autocomplete=off type='text' value='" + calEvent.title + "' />" +
"</div>");
form.append("<input type=hidden value='" + eventID + "' /> ");
form.append("<div class='controls'>" +
"<button type='submit'> Save </button>");
var div = bootbox.dialog(form,
[
{
"label" : "Delete",
"callback": function() {
deleteOrNot = confirm("Sure ??");
if (deleteOrNot) {
calendar.fullCalendar('removeEvents' , function(ev){
$.ajax({
url: '<?=site_url("admin/calendar/delete");?>',
data: 'id='+ eventID,
type: "POST"
});
return (ev._id == calEvent._id);
})
}
}
}
]);
$("#changeName").submit(function() {
calEvent.title = form.find("input[name=title]").val();
calEvent.description = form.find("input[name=description]").val();
calEvent.id = form.find("input[type=hidden]").val();
$.ajax({
url: '<?=site_url("admin/calendar/editTitle");?>',
data: 'title='+ calEvent.title+'&id='+ calEvent.id,
type: "POST"
});
calendar.fullCalendar('updateEvent', calEvent);
div.modal("hide");
return false;
});
}
In your delete process...you shouldn't be relying on the global eventID, rather just getting the ID from specific event
Change:
if(!eventID){
eventID = calEvent._id;
}
To:
var eventID = calEvent._id;
I suspect you also have a problem within drop by using the global eventID when dropping more than one at a time. Would have to see what // some methods here does.
What I would suggest is getting rid of the global eventID completely. When adding, wait for the id to be returned from server before passing the data to fullCalandar within your success callback
Similarly...within deleteOrNot...should make ajax request first, then only call the calendar.fullCalendar('removeEvents' within success callback of $.ajax. This will give confirmation of ajax success before user sees event removed. If ajax fails, user won't know using your approach

Ajax submit of data array in CakePHP not working

I'm making making a scheduling calendar where schedulers can drag and drop members of an organization onto Fullcalendar. I have gotten as far as storing dropped events in an array Object, arrayOfEvents. I want to make an Ajax submit to a CakePHP add function to insert the data into my events database and then reload the calendar. Here's my code.
External events to drop:
/* initialize the external events
-----------------------------------------------------------------*/
$('#external-events div.external-event').each(function() {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject = {
title: $.trim($(this).text()), // use the element's text as the event title
userId: this.id
};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject);
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
Fullcalendar:
/* initialize the calendar
-----------------------------------------------------------------*/
var arrayOfEvents = [];
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'agendaWeek,agendaDay'
},
defaultView: 'agendaWeek',
editable: true,
events: [
<?php foreach ($users as $user) {
foreach ($user['Event'] as $event):
?>
{
start: '<?php echo $event['start_date']; ?>',
end: '<?php echo $event['end_date']; ?>',
title: '<?php echo $event['title']; ?>',
allDay: false,
color: '#077169'
},
<?php endforeach;
}
?>
],
droppable: true, // this allows things to be dropped onto the calendar !!!
drop: function(date, allDay) { // 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.end = (date.getTime() + 3600000) / 1000; // default shift length is 1 hour
copiedEventObject.userId = originalEventObject.userId;
copiedEventObject.allDay = false;
// 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);
// Push events into array
arrayOfEvents.push(copiedEventObject);
//todo: the calendar needs to insert events into the event calendar.
console.log(arrayOfEvents);
}
});
});
Update Schedule function called on a link:
function updateSchedule()
{
var arrayOfEvents = [];
//var data = "numOfEvents=" + arrayOfEvents.length; //original
var data = "numOfEvents=" + arrayOfEvents.length;
// You can get all events out of the array here
for (var i = 0; i < arrayOfEvents.length; i++) {
var event = arrayOfEvents[i];
data += "&id" + i + "=" + event.id
+ "&start" + i + "=" + event.start
+ "&end" + i + "=" + event.end;
}
// Make your ajax post here
$.ajax({
type: "POST",
url: "<?php echo $this->webroot; ?>events/add",
data: data,
success: function(response) {
alert('done!');
},
fail: function(response) {
alert("error");
}
});
Cakephp events/add function:
public function add() {
$this->autoRender = false;
if ($this->RequestHandler->isAjax()) {
Configure::write('debug', 0);
}
if (!empty($this->data)) {
if ($this->Event->save($this->data)) {
echo 'Record has been added';
} else {
echo 'Error while adding record';
}
}
}
I know this is a long one but any input would be well received.

Categories

Resources