Ajax submit of data array in CakePHP not working - javascript

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.

Related

Show time on event mouse hover using Full calendar

I am using Fullcalendar, get call event id on event mouse hover, this event id passes in ajax call for getting the record from the database based on event id. Issue is that how to pass variable out of ajax success function. I am doing like this way
eventMouseover: function(calEvent) {
var start;
var end;
$.ajax({
url: js_base_path+ 'calendar/get_date_time/'+calEvent.id,
type:"GET",
dataType:"json",
success:function(data){
start = data.start_datetime;
end = data.end_datetime;
},
});
var realstart;
if(start == '00.00')
{
realstart = calEvent.title;
}
else
{
realstart = start+ ' - ' + end + ': ' +calEvent.title;
}
$(this).popover({
title: realstart,
content: calEvent.description,
trigger: 'hover',
template: popfunction(calEvent.borderColor),
placement: "top",
atMouse: true,
container: 'body'
}).popover('show');
},
I am facing this error when event mouse hover
Uncaught ReferenceError: start is not defined
This is my controller function
public function get_date_time($id)
{
$results = $this->calendar->get_calendar_row($id);
$data['start_datetime'] = date("H:i", strtotime($results->from_date_time));
$data['end_datetime'] = date("H:i", strtotime($results->to_date_time));
echo json_encode($data);
}

full calendar event drop is not working

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)

how to get values from db and insert them to events array

My code is as below.
<script>
var t=<?php echo json_encode($ta)?>;
var d=<?php echo json_encode($da)?>;
$(document).ready(function() {
$('#calendar').fullCalendar({
//defaultDate: '2016-03-12',
editable: true,
eventLimit: true, // allow "more" link when too many events
//$r=$ev->title;
for(var j=0;j<d.length;j++)
{
events: [{
title: t[j],
start: d[j]
}
]
}
});
});
</script>
I have used the fullcalendar 2.6.1. But nothing displayed. Please can anybody help me? I want to retrieve all the title and eventDate from the db and view in the calendar. The var t and d contains the all the data of $ta and $da arrays. I just wanted to assign them to events array title and start keywords.There are some red marks indicate that for loop is going to be wrong.
Try this one
<?php
$ta=array();
$i=0;
?>
#foreach($events as $ev)
<?php
$ta[$i]['title'] = $ev->title;
$ta[$i]['start'] = date('Y-m-d H:i:s', strtotime($ev->eventDate));
$i++;
?>
#endforeach
<script>
var t=<?php echo json_encode($ta)?>;
$(document).ready(function() {
$('#calendar').fullCalendar({
//defaultDate: '2016-03-12',
editable: true,
eventLimit: true, // allow "more" link when too many events
events: t,
eventRender: function(event, element) {
$('.fc-time', element).hide();
}
});
});
</script>
$.ajax({
url:'',
dataType: 'json',
success: function(doc) {
var events = [];
$.each(doc, function(key, value){
events.push({
title : value['title name'],
start : value['hours'],
backgroundColor: Metronic.getBrandColor('yellow'),
id : value['id']
});
});
AddFullCalenderEvent(events);
}
});
function AddFullCalenderEvent(eventList){
$('#calendar').fullCalendar({
events: eventList,
eventClick: function(event) {
// opens events in a popup window
window.location.href = "pagename?id=" + event.id;
return false;
}
Try this

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

Categories

Resources