I am currently working away with FullCalendar, which is pretty cool and has done a lot of neat stuff for me. The only problem I'm having is that if I edit an event, and then try and create another event the javascript seems to hold onto the initial events data.
I am using calendar.fullCalendar('unselect') when I need the link to end, but it doesn't seem to make a difference no matter what I do. I'm hoping you guys might be able to see something I'm overlooking.
<script type='text/javascript'>
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultView: 'agendaWeek',
selectable: true,
unselectAuto: true,
selectHelper: true,
editable: true,
select: function(start, end, allDay) {
//var title = prompt('Event Title:');
//var desc = prompt('Event Description:');
//calendar.fullCalendar('unselect');
$('#eventStart').val(start);
$('#eventEnd').val(end);
$('#eventAllDay').val(allDay);
$('#formName').fadeIn();
$('.closeSchedule a').click(function(){
$('#formName').fadeOut('slow');
$('#calendar').fullCalendar('unselect');
//alert(jsEvent);
});
},
events: [
<?php
$first = true;
foreach ($events as $event)
{
if ($first == true)
{
$comma = '';
$first = false;
}
else
{
$comma = ',';
}
echo $comma."
{
id: '".$event->id."',
title: '".addSlashes($event->title)."',
start: '".$event->start."',
end: '".$event->end."',
allDay: ".$event->allDay."
}";
$first = false;
}
?>
],
eventClick: function(event) {
//alert(event.id);
$.ajax({
url: './schedule/getEdit/'+event.id,
success: function(data) {
var formEmpty = $('formName').html();
$('#formName').html(data);
$('#formName').fadeIn('fast');
$('.closeSchedule a').click(function(){
$('#formName').fadeOut('slow');
$('#calendar').fullCalendar('unselect');
});
$('#deleteEvent').live('click', function(){
var answer = confirm("Are you sure you wish to delete this event?")
if (answer){
$.ajax({
type: "POST",
url: "./schedule/deleteEvent/"+event.id,
success: function(msg){
$('#formName').fadeOut('fast');
calendar.fullCalendar( 'removeEvents', [event.id ] )
$('#calendar').fullCalendar('unselect');
}
});
}
});
$('#updateEvent').live('click', function(){
var title = $('#eventName').val();
var trainerID = $('#eventTrainer').val();
var trainer = $('#eventTrainer option:selected').text();
var classID = $('#eventType').val();
var eventType = $('#eventType option:selected').text();
var eventStart = $('#eventStart').val();
var eventEnd = $('#eventEnd').val();
var eventAllDay = $('#eventAllDay').val();
if (eventAllDay == 'false')
{
allDay = false;
}
else
{
allDay = true;
}
// This runs the ajax to add the event to the database.
newData = 'title='+title+'&trainerID='+trainerID+'&classID='+classID+'&start='+eventStart+'&end='+eventEnd+'&allDay='+allDay
$.ajax({
type: "POST",
url: "./schedule/updateEvent/"+event.id,
data: newData,
success: function(msg){
event.title = title;
calendar.fullCalendar('rerenderEvents');
//calendar.fullCalendar('unselect');
$('#calendar').fullCalendar('unselect');
}
});
$('#formName').fadeOut('fast');
$('#eventName').val('');
$('#eventTrainer').val();
$('#eventType').val();
});
}
});
},
eventDrop: function(event,dayDelta,minuteDelta,allDay,revertFunc) {
newData = 'start='+event.start+'&end='+event.end+'&allDay='+allDay
$.ajax({
type: "POST",
url: "./schedule/updateEventTime/"+event.id,
data: newData,
success: function(msg){
}
});
},
eventResize: function(event,dayDelta,minuteDelta,revertFunc) {
newData = 'start='+event.start+'&end='+event.end+'&allDay='+event.allDay
$.ajax({
type: "POST",
url: "./schedule/updateEventTime/"+event.id,
data: newData,
success: function(msg){
}
});
}
});
$('#submitEvent').click(function(){
$('#calendar').fullCalendar('unselect');
var title = $('#eventName').val();
var trainerID = $('#eventTrainer').val();
var trainer = $('#eventTrainer option:selected').text();
var classID = $('#eventType').val();
var eventType = $('#eventType option:selected').text();
var eventStart = $('#eventStart').val();
var eventEnd = $('#eventEnd').val();
var eventAllDay = $('#eventAllDay').val();
if (eventAllDay == 'false')
{
allDay = false;
}
else
{
allDay = true;
}
// This runs the ajax to add the event to the database.
newData = 'title='+title+'&trainerID='+trainerID+'&classID='+classID+'&start='+eventStart+'&end='+eventEnd+'&allDay='+allDay
$.ajax({
type: "POST",
url: "./schedule/addEvent",
data: newData,
success: function(msg){
var description = '<ol><li>'+title+'</li><li>'+trainer+'</li><li>'+eventType+'</li><li class="eventID hide">'+msg+'</li>';
calendar.fullCalendar('renderEvent',
{
id: msg,
title: title,
description: description,
start: eventStart,
end: eventEnd,
allDay: allDay
},
true // make the event "stick"
);
calendar.fullCalendar('unselect');
//calendar.fullCalendar( 'rerenderEvents' )
}
});
$('#formName').fadeOut('fast');
$('#eventName').val('');
$('#eventTrainer option:selected').removeAttr('selected');
$('#eventType option:selected').removeAttr('selected');
});
});
</script>
At this point, I feel like I've tried it all, and I'm just hoping a fresh set of eyes will see what I missed.
Ok took a quick look it looks like you aren't initializing the form with a blank form for the add action in the "select:" function of your full calendar:
In your event click you are doing this:
$('#formName').html(data);
I don't see where you are clearing that with a blank form for a new event. (might have just missed it there is a lot of code there)
Let me know.
Related
I wanna create array from ajax response. I took array from ajax and i have to create dynamic data for chips
materializecss autocomplete
response from ajax
var tag = '';
$(document).on('keyup', '.tags', function() {
var _this = $(this).val();
if(_this.length > 1) {
$.ajax({
url: '/story/searchTags',
type: 'POST',
dataType: 'JSON',
data: {
tag: _this
},
success: function(tags) {
tag = tags;
}
});
}
});
$('.chips-placeholder').chips({
placeholder: lang_('Your tag'),
secondaryPlaceholder: '+ tag',
autocompleteOptions: {
// I need data like this from response
data: {
'Google', null
'Googol', null
},
limit: 5,
minLength: 2
}
});
<div class="chips chips-placeholder chips-autocomplete input-field" style="background:#fff">
<input class="input tags" placeholder="tag" autocomplete="off" />
</div>
that's my code
Finally, thanks to #Vel to find right answer.
jsfiddle - work code
You need to do like this.
var tag = '';
$(document).on('keyup', '.tags', function() {
var _this = $(this).val();
if(_this.length > 1) {
/*$.ajax({
url: '/story/searchTags',
type: 'POST',
dataType: 'JSON',
data: {
tag: _this
},
success: function(tags) {
tag = tags;
}
});*/
// ['google', 'googol'] <- this array I take from ajax
tag = ['google', 'googol'];
var obj = {};
$(tag).each(function (index, value) {
obj[value] = null;
});
$('.chips').chips({
secondaryPlaceholder: '+ tag',
autocompleteOptions: {
data:obj,
}
});
}
});
fiddle link
I'm trying to make this code to work but it look I'm doing something wrong when passing the two variables with ajax, please help, here is the code, basically is a drag and drop code to move items between boxes and organize inside each box.
<script type="text/javascript">
$(document).ready(function() {
// Example 1.3: Sortable and connectable lists with visual helper
$('#sortable-div .sortable-list').sortable({
connectWith: '#sortable-div .sortable-list',
placeholder: 'placeholder',
delay: 150,
stop: function() {
var selectedData = new Array();
$('.sortable-list>li').each(function() {
selectedData.push([$(this).attr("id"), $(this).attr("pagenum")])
});
updateOrder(selectedData);
}
});
});
function updateOrder(data) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: data,
page: data
},
success: function() {
/* alert('your change successfully saved');*/
}
})
}
</script>
You can make it using this way:
$('.spremiUredivanje').click(function(){
ai = document.getElementById('ai_mjerila_edit').value;
broj_mjerila = document.getElementById('broj_mjerila_edit').value;
adresa = document.getElementById('adresa_edit').value;
stanje = document.getElementById('stanje_edit').value;
$( "#datum_edit" ).datepicker( "option", "dateFormat", "yy-mm-dd" );
datum = document.getElementById('datum_edit').value;
operater = document.getElementById('operater_edit').value;
$.ajax({
url: 'test.php',
type: 'POST',
data: {
post1: broj_mjerila, post2: adresa, post3:stanje, post4: datum, post5: operater, post6:ai
},
beforeSend: function(){
$('#loaderEdit').show();
},
So your php file should look like this:
$broj_mjerila = $_POST['post1'];
$adresa = $_POST['post2'];
$stanje = $_POST['post3'];
$datum = $_POST['post4'];
$operater = $_POST['post5'];
$ai = $_POST['post6'];
To control your response use success inside ajax call:
success: function(response) {
if(response == 1) {
//alert("success!");
$('#editUspjesan').show();
$('#loaderEdit').hide();...
Can you explain your requirement clear. Are you trying to get page number and id in 2 separate array?
// If page no and id need to be in separate array
var position = [], pages = [];
$('.sortable-list>li').each(function() {
position.push($(this).attr("id"));
pages.push($(this).attr("pagenum"));
});
updateOrder(position, pages);
function updateOrder(position, page) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: position,
page: page
},
success: function() {
/* alert('your change successfully saved');*/
}
})
}
// If page no and id can be combined use objects
var selectedData = [];
$('.sortable-list>li').each(function() {
selectedData.push({id: $(this).attr("id"), page: $(this).attr("pagenum")})
});
function updateOrder(data) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: data
},
success: function() {
/* alert('your change successfully saved');*/
}
})
}
<script type="text/javascript">
$(document).ready(function() {
// Example 1.3: Sortable and connectable lists with visual helper
$('#sortable-div .sortable-list').sortable({
connectWith: '#sortable-div .sortable-list',
placeholder: 'placeholder',
delay: 150,
stop: function() {
var selectedData = new Array();
$('.sortable-list>li').each(function() {
selectedData.push([$(this).attr("id"), $(this).attr("pagenum")])
});
updateOrder(selectedData);
}
});
});
function updateOrder(data) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: data.id,
page: data.pagenum
},
dataType:'json',
success: function() {
/* alert('your change successfully saved');*/
}
})
}
</script>
Let's try this one
I'd like to color events according to database. I use eventRender. Here is the whole code:
$(document).ready(function() {
var date = new Date();
var calendar = $('#calendar').fullCalendar({
header:
{
left: 'prev,next ',
center: 'title',
right: 'today'
},
selectable: true,
selectHelper: true,
fixedWeekCount: false,
allDayDefault: true,
editable: true,
events: "http://localhost/calendar_directory/calendar_db_connect.php",
eventRender: function (event, element, view)
{
if (event.confirmed == 0)
{
event.color = "#FFB999";
}
else
{
event.color = "#528881";
}
},
select: function(start, end) {
var title;
var beforeToday = false;
var check = $.fullCalendar.formatDate(start, "YYYY-MM-DD");
var today = $.fullCalendar.formatDate(moment(), "YYYY-MM-DD");
if(check < today)
{
beforeToday = true;
}
else
{
title = prompt('Event Title:');
}
if (title && !beforeToday)
{
var start = $.fullCalendar.formatDate(start, "YYYY-MM-DD");
var end = $.fullCalendar.formatDate(end, "YYYY-MM-DD");
$.ajax(
{
url: 'http://localhost/calendar_directory/add_events.php',
data: 'title='+ title+'&start='+ start +'&end='+ end ,
type: "POST",
success: function(json)
{
}
});
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
},
true // make the event "stick"
);
}
calendar.fullCalendar('unselect');
},
eventClick: function(event, jsEvent, view)
{
//set the values and open the modal
$("#eventInfo").html(event.description);
$("#eventLink").attr('href', event.url);
$("#eventContent").dialog({ modal: true, title: event.title });
},
eventDrop: function(event, delta)
{
var check = $.fullCalendar.formatDate(event.start, "YYYY-MM-DD");
var today = $.fullCalendar.formatDate(moment(), "YYYY-MM-DD");
if(check < today) {
alert('Select an other start time, after today!');
}
else
{
var start = $.fullCalendar.formatDate(event.start, "YYYY-MM-DD");
var end = $.fullCalendar.formatDate(event.end, "YYYY-MM-DD");
$.ajax(
{
url: 'http://localhost/calendar_directory/update_events.php',
data: 'title='+ event.title+'&start='+ start +'&end='+ end +'&id='+ event.id ,
type: "POST",
});
}
},
eventResize: function(event)
{
var start = $.fullCalendar.formatDate(event.start, "YYYY-MM-DD");
var end = $.fullCalendar.formatDate(event.end, "YYYY-MM-DD");
$.ajax(
{
url: 'http://localhost/calendar_directory/update_events.php',
data: 'title='+ event.title+'&start='+ start +'&end='+ end +'&id='+ event.id ,
type: "POST",
});
},
eventClick: function(event)
{
var decision = confirm("Do you really want to confirm that?");
if (decision)
{
$.ajax(
{
url: "http://localhost/calendar_directory/confirm_events.php",
data: "&id=" + event.id,
type: "POST",
success: function(json)
{
console.log("confirmed");
//event.backgroundColor = 'green';
//$('#calendar').fullCalendar( 'rerenderEvents' );
}
});
}
}
});
(Please ignore clickEvent for modal).
The problem is, that it does not change the color of the events for the first time (first load of the page). But when I drop/resize an event all events gets the right color.
Before drop
After drop
table structure:
id - int, PR
title - varchar
start -datetime
end -datetime
confirmed - int (can be 0 or 1) <- The color should be change according to this
The eventRender method runs after the corresponding CSS for the event has been created. Therefore changing the properties of the event which relate to formatting/rendering at this point in the process has no effect - they have already been processed.
Luckily, you also get the "element" parameter passed to you in the callback - this gives you access to the rendered HTML, which you can then manipulate.
Setting the "color" property of an event actually affects the background and border colours of the rendered element, so we can replace what you did with:
eventRender: function (event, element, view)
{
if (event.confirmed == 0)
{
element.css("background-color", "#FFB999");
element.css("border-color", "#FFB999");
}
else
{
element.css("background-color", "#528881");
element.css("border-color", "#528881");
}
}
This should have the desired effect. Arguably this is a bug/undesirable feature in fullCalendar - you'd want to still be able to manipulate the event's properties fully and expect them to take effect. On the other hand, getting the "element" parameter effectively gives you full control over the rendering of the event, more than you would just via setting the event's properties. If this method ran before the element was created, you wouldn't have access to the element, with all the extra power that gives you. So it's a trade-off, but it's worth understanding the internals in order to know what you can change, and when in the process you can do it.
If I have one ajax call with a long foreach loop where I update a text file, and at the same time I want to read that file and display changed content from the first call by another second call, how can I achieve that?
When the first runs, the second waits until the first one has finished.
I want to run the first and second at the same time. In the second call, every second I want to check the state inside the file created by the first call - something like a progress bar.
function startTimer(){
timer = window.setInterval(refreshProgress, 1000);
}
function refreshProgress(){
$.ajax({
type: "POST",
url: '/index.php?/system/run_progress_checker',
dataType:"json",
success: function(data)
{
console.log(data);
if (data.percent == 100) {
window.clearInterval(timer);
timer = window.setInterval(completed, 1000);
}
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
function completed() {
//$("#message").html("Completed");
window.clearInterval(timer);
}
$(".systemform").submit(function(e) { //run system
$.when(startTimer(),run_system()).then(function(){});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
function run_system(){
$("#leftcontainer").html("");
$("#leftcontainer").show();
$("#chartContainer").hide();
$(".loading").show();
var sysid = $(".sysid:checked").val();
var oddstype = $(".odds_pref").val();
var bettypeodds = $(".bet_type_odds").val();
var bookie = $(".bookie_pref").val();
if (typeof oddstype === "undefined") {
var oddstype = $(".odds_pref_run").val();
var bettypeodds = $(".bet_type_odds_run").val();
var bookie = $(".bookie_pref_run").val();
}
$.ajax({
type: "POST",
url: '/index.php?/system/system_options/left/'+'1X2/'+oddstype+'/'+bettypeodds+'/'+bookie,
data: {
system : sysid,
showpublicbet : showpublicbet }, // serializes the form's elements.
dataType:"json",
success: function(data)
{
console.log(data);
$("#systemlist").load('/index.php?/system/refresh_system/'+sysid,function(e){
systemradiotocheck();
});
$("#resultcontainer").load('/index.php?/system/showresults/'+sysid+'/false');
$("#resultcontainer").show();
$("#leftcontainer").html(data.historic_table);
$("#rightcontainer").html(data.upcoming_table);
var count = 0;
var arr = [];
$("#rightrows > table > tbody > tr").each(function(){
var row = $(this).data('row');
if(typeof row !== 'undefined'){
var rowarr = JSON.parse(JSON.stringify(row));
arr[count] = rowarr;
$(this).find('td').each(function(){
var cell = $(this).data('cell');
if(typeof cell !== 'undefined'){
var cellarr = JSON.parse(JSON.stringify(cell));
arr[count][6] = cellarr[0];
}
});
count ++;
}
});
if(oddstype == "EU" && bookie == "Bet365"){
$('.bet365').show();
$('.pinnacle').hide();
$('.ukodds').hide();
}
if(oddstype == "EU" && bookie == "Pinnacle"){
$('.pinnacle').show();
$('.bet365').hide();
$('.ukodds').hide();
}
if(oddstype == "UK"){
$('.bet365').hide();
$('.pinnacle').hide();
$('.ukodds').show();
}
if(bookie == "Pinnacle"){
$(".pref-uk").hide();
}
else{
$(".pref-uk").show();
}
$(".loading").hide();
runned = true;
var options = {
animationEnabled: true,
toolTip:{
content: "#{x} {b} {a} {c} {y}"
},
axisX:{
title: "Number of Games"
},
axisY:{
title: "Cumulative Profit"
},
data: [
{
name: [],
type: "splineArea", //change it to line, area, column, pie, etc
color: "rgba(54,158,173,.7)",
dataPoints: []
}
]
};
//console.log(data);
var profitstr = 0;
var parsed = $.parseJSON(JSON.stringify(data.export_array.sort(custom_sort)));
var counter = 0;
for (var i in parsed)
{
profitstr = profitstr + parsed[i]['Profit'];
//console.log(profitstr);
var profit = parseFloat(profitstr.toString().replace(',','.'));
//console.log(profit);
var event = parsed[i]['Event'].toString();
var hgoals = parsed[i]['Home Goals'].toString();
var agoals = parsed[i]['Away Goals'].toString();
var result = hgoals + ":" + agoals;
var date = parsed[i]['Date'].toString();
var bettype = parsed[i]['Bet Type'];
var beton = parsed[i]['Bet On'];
var handicap = parsed[i]['Handicap'];
//alert(profitstr);
//alert(profit);
//options.data[0].name.push({event});
counter++;
options.data[0].dataPoints.push({x: counter,y: profit,a:event,b:date,c:result});
}
$("#chartContainer").show();
$("#chartContainer").CanvasJSChart(options);
$(".hidden_data").val(JSON.stringify(data.export_array));
$(".exportsys").removeAttr("disabled");
$(".exportsys").removeAttr("title");
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
Backend part is not so important because it works.
Sounds like a great case for jQuery's $.when $.then. In the first part, the $.when, you'll have the first ajax call, and when that is finished... you can port the data from the first part to the $.then part. For example:
$.when(
//perform first ajax call and pass this data to the 'then'.
$.ajax(
{
type: "POST",
url: "<<insert url>>",
contentType: "application/json; charest=utf-8",
success: function (data) {
//process data
},
error: function (XMLXHttpRequest, textStatus, errorThrown) {
}
})
).then(function (data, textStatus, jqXHR) {
var obj = $.parseJSON(data); // take data from above and use it to perform second ajax call.
var params = '{ "CustomerID": "' + obj[0].CustomerID + '" }';
$.ajax(
{
type: "POST",
url: "<<insert url>>",
data: params,
contentType: "application/json; charest=utf-8",
success: function (data) {
//process data
},
error: function (XMLXHttpRequest, textStatus, errorThrown) {
}
})
});
}
});
So I managed to follow one of the tutorials for the fullcalendar script to hook up the jquery based calendar to my MySQL database, allowing me to write and read calendar events into the database.
The variables handed over from jquery to mysql are things such as the unique event ID, start date, end date, title, etc. but sadly, not the tab color of the event. Since I am using draggable "external events", which basically are draggable buttons that you can drag n drop onto the calendar (which naturally all have different colors), I am now having the problem that I cannot make fullcalendar extract the color of the div and then pass it over via PHP into my MySQL database.
So here is the question:
How can I adjust the jquery script to extract the var color = event.backgroundColor; variable and add it on to my php script?
I have no clue about jquery nor javascript, hence would really appreciate help. I also tried to throw a few bucks towards a freelance programmer but even he ultimately gave up.
Here the code I have so far:
Fullcalendar script in calendar.php
<script>
$(document).ready(function() {
var zone = "08:00"; //Change this to your timezone
$.ajax({
url: 'process.php',
type: 'POST', // Send post data
data: 'type=fetch',
async: false,
success: function(s){
json_events = s;
}
});
var currentMousePos = {
x: -1,
y: -1
};
jQuery(document).on("mousemove", function (event) {
currentMousePos.x = event.pageX;
currentMousePos.y = event.pageY;
});
/* initialize the external events
-----------------------------------------------------------------*/
$('#external-events .external-event').each(function() {
// store data so the calendar knows to render an event upon drop
$(this).data('event', {
title: $.trim($(this).html()), // use the element's text as the event title
//color: $.trim($(this).backgroundColor()), // use the element's bgcolor as the events background
stick: true // maintain when user navigates (see docs on the renderEvent method)
});
// 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
});
});
/* initialize the calendar
-----------------------------------------------------------------*/
$('#calendar').fullCalendar({
events: JSON.parse(json_events),
//events: [{"id":"14","title":"New Event","start":"2015-01-24T16:00:00+04:00","allDay":false}],
utc: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
droppable: true,
slotDuration: '00:30:00',
eventReceive: function(event){
var title = event.title;
var start = event.start.format("YYYY-MM-DD[T]HH:mm:SS");
var color = event.backgroundColor;
$.ajax({
url: 'process.php',
data: 'type=new&title='+title+'&startdate='+start+'&zone='+zone+'&color='+color,
type: 'POST',
dataType: 'json',
success: function(response){
event.id = response.eventid;
$('#calendar').fullCalendar('updateEvent',event);
},
error: function(e){
console.log(e.responseText);
}
});
$('#calendar').fullCalendar('updateEvent',event);
console.log(event);
},
eventDrop: function(event, delta, revertFunc) {
var title = event.title;
var start = event.start.format();
var end = (event.end == null) ? start : event.end.format();
var color = event.backgroundColor;
$.ajax({
url: 'process.php',
data: 'type=resetdate&title='+title+'&start='+start+'&end='+end+'&eventid='+event.id+'&color='+color,
type: 'POST',
dataType: 'json',
success: function(response){
if(response.status != 'success')
revertFunc();
},
error: function(e){
revertFunc();
alert('Error processing your request: '+e.responseText);
}
});
},
eventClick: function(event, jsEvent, view) {
console.log(event.id);
var title = prompt('Event Title:', event.title, { buttons: { Ok: true, Cancel: false} });
if (title){
event.title = title;
console.log('type=changetitle&title='+title+'&eventid='+event.id);
$.ajax({
url: 'process.php',
data: 'type=changetitle&title='+title+'&eventid='+event.id,
type: 'POST',
dataType: 'json',
success: function(response){
if(response.status == 'success')
$('#calendar').fullCalendar('updateEvent',event);
},
error: function(e){
alert('Error processing your request: '+e.responseText);
}
});
}
},
eventResize: function(event, delta, revertFunc) {
console.log(event);
var title = event.title;
var end = event.end.format();
var start = event.start.format();
var color = event.backgroundColor;
$.ajax({
url: 'process.php',
data: 'type=resetdate&title='+title+'&start='+start+'&end='+end+'&eventid='+event.id+'&color='+color,
type: 'POST',
dataType: 'json',
success: function(response){
if(response.status != 'success')
revertFunc();
},
error: function(e){
revertFunc();
alert('Error processing your request: '+e.responseText);
}
});
},
eventDragStop: function (event, jsEvent, ui, view) {
if (isElemOverDiv()) {
var con = confirm('Are you sure to delete this event permanently?');
if(con == true) {
$.ajax({
url: 'process.php',
data: 'type=remove&eventid='+event.id,
type: 'POST',
dataType: 'json',
success: function(response){
console.log(response);
if(response.status == 'success'){
$('#calendar').fullCalendar('removeEvents');
getFreshEvents();
}
},
error: function(e){
alert('Error processing your request: '+e.responseText);
}
});
}
}
}
});
function getFreshEvents(){
$.ajax({
url: 'process.php',
type: 'POST', // Send post data
data: 'type=fetch',
async: false,
success: function(s){
freshevents = s;
}
});
$('#calendar').fullCalendar('addEventSource', JSON.parse(freshevents));
}
function isElemOverDiv() {
var trashEl = jQuery('#trash');
var ofs = trashEl.offset();
var x1 = ofs.left;
var x2 = ofs.left + trashEl.outerWidth(true);
var y1 = ofs.top;
var y2 = ofs.top + trashEl.outerHeight(true);
if (currentMousePos.x >= x1 && currentMousePos.x <= x2 &&
currentMousePos.y >= y1 && currentMousePos.y <= y2) {
return true;
}
return false;
}
});
</script>
calendar.php - > external events aka the draggable event buttons
<div class="box box-solid">
<div class="box-header with-border">
<h4 class="box-title">Draggable Audits</h4>
</div>
<div class="box-body">
<!-- the events -->
<div id="external-events">
<div class="external-event bg-aqua">FO Check-In</div>
<div class="external-event bg-blue">FO Check-Out</div>
<div class="external-event bg-light-blue">HSKP Room</div>
<div class="external-event bg-teal">Fitness Centre</div>
<div class="external-event bg-yellow">Reservation</div>
<div class="external-event bg-orange">F+B Breakfast</div>
<div class="external-event bg-green">F+B A La Carte</div>
<div class="external-event bg-lime">F+B Chinese</div>
<div class="external-event bg-red">F+B Chinese PDR</div>
<div class="external-event bg-purple">FO Club IC</div>
<div class="external-event bg-fuchsia">F+B Lobby Lounge</div>
<div class="external-event bg-muted">Ballroom Event</div>
<div class="external-event bg-navy">SEC Fire Drill</div>
<div class="checkbox">
<label for="drop-remove">
<input type="checkbox" id="drop-remove">
remove after drop
</label>
</div>
<button id="trash" type="button" class="btn btn-primary btn-danger btn-lg">DRAG HERE TO DELETE</button>
</div>
</div>
<!-- /.box-body -->
</div>
process.php script that handles the reading and writing into the MySQL table
(Note: fetching the color field works fine, but I have no way of writing the color data into the table since I cant extract the event.backgroundcolor() variable from jquery)
<?php
session_start();
include '../plugins/MySQL/connect_db.php';
$con = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
$type = $_POST['type'];
$holidex = $_SESSION['Holidex'];
if($type == 'new')
{
$startdate = $_POST['startdate'].'+'.$_POST['zone'];
$title = $_POST['title'];
$color = $_POST['color'];
$insert = mysqli_query($con,"INSERT INTO calendar(`title`, `startdate`, `enddate`, `allDay`, `color`, `holidex`) VALUES('$title','$startdate','$startdate','true','$color','$holidex')");
$lastid = mysqli_insert_id($con);
echo json_encode(array('status'=>'success','eventid'=>$lastid));
}
if($type == 'changetitle')
{
$eventid = $_POST['eventid'];
$title = $_POST['title'];
$update = mysqli_query($con,"UPDATE calendar SET title='$title' where id='$eventid' and holidex='$holidex'");
if($update)
echo json_encode(array('status'=>'success'));
else
echo json_encode(array('status'=>'failed'));
}
if($type == 'resetdate')
{
$title = $_POST['title'];
$startdate = $_POST['start'];
$enddate = $_POST['end'];
$eventid = $_POST['eventid'];
$update = mysqli_query($con,"UPDATE calendar SET title='$title', startdate = '$startdate', enddate = '$enddate', holidex = '$holidex' where id='$eventid' and holidex='$holidex'");
if($update)
echo json_encode(array('status'=>'success'));
else
echo json_encode(array('status'=>'failed'));
}
if($type == 'remove')
{
$eventid = $_POST['eventid'];
$delete = mysqli_query($con,"DELETE FROM calendar where id='$eventid' and holidex='$holidex'");
if($delete)
echo json_encode(array('status'=>'success'));
else
echo json_encode(array('status'=>'failed'));
}
if($type == 'fetch')
{
$events = array();
$query = mysqli_query($con, "SELECT * FROM calendar where holidex='$holidex'");
while($fetch = mysqli_fetch_array($query,MYSQLI_ASSOC))
{
$e = array();
$e['id'] = $fetch['id'];
$e['title'] = $fetch['title'];
$e['start'] = $fetch['startdate'];
$e['end'] = $fetch['enddate'];
$allday = ($fetch['allDay'] == "true") ? true : false;
$e['allDay'] = $allday;
$e['color'] = $fetch['color'];
array_push($events, $e);
}
echo json_encode($events);
}
?>