Home / jQuery / Fullcalendar CRUD with jQuery and PHP

Fullcalendar CRUD with jQuery and PHP

Fullcalendar CRUD (Create,Read,Update,Delete) will enhance your application in terms of Readability, Usabilty, Ease of access, Better UI and various other benefits. Fullcalendar is a virtual calendar that can save events for future reference. There are various features you can benefit out of it but we will only see how to Create, Retrieve, Update and Delete (CRUD).

The Logic

Let us not worry about how Fullcalendar works because we have everything handy. Our objective is to add events to database and update them using a unique ID. We will be using ajax requests to send event details such as title, start date and end date. Once the event is successfully added to the database we will receive a response which will contain a unique ID for the recently added event. So this ID will be used to manage operations on an event.

Table Structure

HTML

There is nothing complex in the design. Create a <div> with an id attribute to invoke fullcalendar using the same. Create another elements with some ID for the external events.

jQuery

Initialize the Fullcalendar plugin on id calendar.

That’s it! Now you can run your page and notice that the fullcalendar plugin will work without flaw. You can play with the the fullcalendar by adding events, modifying dates, adding time, etc but when you refresh the page, everything will go off. Let us now look into the event handlers to send ajax requests based on user actions.

After initializing fullcalendar, we need to add header buttons, set the events to be editable and accept drop event when a user adds a new event.
Add your location timezone: This is required

Adding a new event

When an event is dropped in the calendar the eventReceive event is triggered. At this point we have to get the event title, event start date and time, event end date and time.
For any new event start and end dates are the same.

As fullcalendar uses moment plugin, we need to format the raw time generated in the callback function(event). On successful ajax request get the id stored in database and update the id of new event. For the event to take effect you need to update the calendar.

PHP: Add new event

Renaming the event

When an event is clicked anything can happen based on our code. In this tutorial we will show a popup asking the user to rename the event. The event eventClick is trigger when an event is clicked.

PHP: Change Event Title

Changing Date Range of an event

When an event’s date is modified by resizing the event the eventResize is triggered. Now we send an ajax request with title, start date, end date and ID of the event to process.php and update the event in the database.

Dropping an existing event to another date

When an existing event is dropped into another date the eventDrop is triggered. In the callback you can notice the revertFunc which can be used to move back the event to its original date if the ajax fails.

So when eventDrop is triggered we send the title, start date, end date and ID of the event for update. On return success we do nothing but if not simply call the revertFunc callback.

PHP: Modify Date for an Event

Retrieve the stored events

We have now created and updated the events, let us see how to read the events and populate them on page load.

The format required for the fullcalendar to load events during page load should be exactly like the one shown below,

PHP: Fetch all events from Database

Delete an event by drag and drop

An event can be deleted in ways but I chose the most user friendly way which is Drag and Drop. As I started coding I felt it to be a bit complex but I reminded myself that coding with passion will always give amazing outputs 😉

First set the co-ordinates of the mouse to (-1,-1) during page load. When the mouse moves capture the x and y co-ordinates and save them to global variables.

I have used eventDragStop to identify if the event is dropped on the trashcan div element.

The isElemOverDiv() is used to check if the mouse is over the trashcan and returns true if its on the trashcan else returns false. If the functions returns true simply pass the event’s ID to process.php and remove the event from database. If the response status of ajax request is success then remove the event from DOM.

PHP: Remove an event from Database

Note:: You should have created the table calendar in the database for the calendar to work.

That’s it! Make your web app more usable and user friendly. Feel free to get help in modifying this app from the comments section below.

Download   Preview

About Ashik

I am a Full Stack Developer and love to work on APIs and Apps. Hardcore lover of Ionic and Laravel <3

Check Also

Weather forecast API using jQuery, Ajax and PHP

Weather forecast API is widely used as widgets in small blogs to huge news website …

  • Rajesh

    HI I have downloaded this calender but the calender is not showing. Is there any isssue with javascript?

    • Asesha George

      you need to create a database test and table name calender

  • Tardis Doctorwho

    nice tutorial i subscribed to the newslettre qnd i still can’t download it’d be great if u could help me out

  • Have you activated your email from your mailbox?

    • Tardis Doctorwho

      no i just copied the part about removing an event bydragging it over the trash

  • Thanh

    Awesome code. Really appreciate making it available. Unbelievable easy to work with and understand.

  • thespencer

    Thank You for this tutorial. There is one issue though. New events will not be deleted from the view.

  • Сергей Петрович

    thanks for the tutorial.

  • C. Mayo

    Very nice work; I think this tutorial will go a long way in helping me build a FullCalendar front end for an existing jobs calendar. I do have a question, though. Does anyone know how to load the events array with ONLY events which fall within the current view? This and all the other PHP tutorials I’ve run across load events with “SELECT * FROM calendar” which, in my case, results in over 11,000 returned records going back to 2008. If I’m viewing a particular day, week or month, I’d much prefer to only have to pull the records with fall within that day, week or month.

  • Sandeep Vellaparambil

    good tutorial. Instead of drag and drop.can you please tell me to add event on clicking particular date.Similarly delete event by click option.

  • Sandeep Vellaparambil

    How to add responsive design to fullcalender,So that it can view in low resolution mobiles

  • Ashik, please help me!
    I can’t delete a new event without refresh to get id.

    • Hi, I did not check this before posting. Thank you for bringing this to my attention. I’ll fix this asap and give you and update.

      • Thanks a lot bro 😀

        • Post updated.. check preview now

          • Excuse me, I don’t understand the change. Can you help me with my file please? http://pastebin.com/HM7S8diD

          • In the ‘eventDragStop’ events you can notice that I have added a new function getFreshEvents() which pulls all events from the database after clearing all the events. I have updated the code in the preview as well as in the downloads.

  • Marco B

    Awesome tutorial, but in the agendaWeek and agendaDay view does not work resizing events

  • Marco B

    Awesome tutorial, but in agendaWeek and agendaDay view not work resizing events…
    It gives me a “ReferenceError: update is not defined”

    • Daniel

      Hi, i’m having the same problem right now, could you solved this? Thanks!

      • Nitrotoxin

        same issue, anyone have a solution?

  • Meison

    Dear Ashik, very well written tutorial. I installed this and it works. However, I found some strength behaviour, that adding a event on WEEKAgenda view, an extra 8 minutes will be added .. ie: on screen, its 8:00, but in the DB, this will be come 8:08. And I can’t add event on 8:30 or 9:30 or any hours:30 ..

    And last but not the least, my browser is complaining : synchronous XMLHttpRequest on the main thread is deprecated … Perhaps there are bugs in those js ??

    • Destiny

      Same “8 plus minutes’ issue for me. And I’ve another problem. It’s almost impossible resize the events in the week window because events have problems keeping the new position

    • HugoC

      The issue is in the string inside format(). Instead of “YYYY-MM-DD[T]HH:MM:SS” ,it must be “YYYY-MM-DD[T]HH:mm:SS”, or else we’re putting the month (MM) in the minutes’ place.

      • Alex

        Perfect!

    • Alex

      I have the same issues as Meison as well (but I get stuck at :11 or :41) and every event defaults to 2:00:00 hours long not 00:30:00 mins

  • Dick Stokkel

    hi Ashik, thanks for publishing and sharing your work.
    I just downloaded your full calendar work but jquery.min.map is not included in your package. When I use the cnd version of jquery.min.map it does not work.
    Do have the version of jQuery.min.map there you are using availalble?

  • Geethu

    Hi Ashik, how to add new event in calendar pls help me

  • Ping Rivero

    Do you know how to include a timepicker for this?

  • khaleader Pc

    this worked for me for the format of dates
    var start = moment(event.start).format(“DD-MM-YYYY HH:mm:ss”);

    • Thank you for the fix 🙂 Featuring this comment.

  • Reduan Kurtaj

    nice tutorial mate!!! everything works fine but i have one question… where can I change the name of the month?

    best regard

  • dfgdf

    Hi , i want to fix time duration in calnder , means 6-9 , 10-1 , , so how to possible . please help.
    Thanks in advence

  • abou

    I’m a downloaded your tutorial for fullcalendar.nice but it doesn’t work

    • Your questions needs more explanation. run it from a local server, you just can’t open index.html file.

  • patrick

    I’m getting a ” Uncaught TypeError: Cannot read property ‘hasTime’ of undefined ” after creating an event and refreshing the page. The event is saved properly in database but the calendar wont load after a refresh and gives that error

    • vikas varma

      @patrick full calendar takes the data in the json format send the data in json format for ex : events={
      title:’watsapp’,
      start:’28/06/1992′
      }
      $(‘#calendar’).fullCalendar(‘renderEvent’,event);
      this will work

      • freddy

        make sure you don’t load jquery twice !

  • LUKI ψ(`∇´)ψ

    I already make a database, and when I drag into the calendar it saved in the database.
    but when I reload the page, why all are gone ?
    but in the database is still exist. I don’t know why. thank you.

  • Keegan

    Hi, is there any way to change the color of the Calender entries based on a DB value? ie. Which User has made the booking??
    Thanks heaps!

  • s3ba

    Hi, nice work – but event resize is not working.
    I think the error is in that line.
    update(title,start,end,event.id);

  • Ocky Harliansyah

    Hi, many thanks for your tutorial.
    This complete guide was really worked for me.

  • G33K1E

    How do I make the week start @ Monday?

    • mohamed

      Hi G33K1E,

      firstDay : 1

      append code for fullcalendar function ..

      working fine ..!

      • G33K1E

        Hello mohamed,

        Thanks for your reply, I’m unsure where to put this tho?

        • mohamed

          Hi G33k1E,

          For Example:

          $(‘#calendar’).fullCalendar({
          titleFormat: ‘MMM dd, yyyy’,
          timeFormat: ‘hh:mm TT { – hh:mm TT}’,
          firstDay : 1,

          });

          put the code for fullcalendar function ..

          • G33K1E

            Thank you very much.

        • mohamed

          Hi G33k1E,

          For Example:

          $(‘#calendar’).fullCalendar({

          titleFormat: ‘MMM dd, yyyy’,

          timeFormat: ‘hh:mm TT { – hh:mm TT}’,

          firstDay : 1,

          });

          put the code for fullcalendar function ..

  • Danny Herremans

    I’m getting a ” Uncaught TypeError: Cannot read property ‘hasTime’ of undefined ” after creating an event and refreshing the page. and Uncaught ReferenceError: jQuery is not defined. The js is linked properly. When i launch the application i see the draggeble events but not the full calender. Any help?

    • mohamed

      Hi Danny

      allDayText : ‘hasTime’ include a text in fullcalendar.. function

  • bharat saraswat

    Thanks for the Tutorial, I was thinking to add some bootstrap labels on the events like important, warning or sucess so how can I store them in the database.
    Thanks.

  • Nevets

    what is the name of the database in your tutorial?

  • marco

    is possible to see the calendar as full year mode?
    Do you think will be possible bind calendar events and when you drag and drop to move one event all bindend event will be moved togheter?

  • it would be awesome if someone would do it in laravel using
    https://github.com/maddhatter/laravel-fullcalendar

  • Will

    Excellent example, very clean code.

  • Adam Yang

    Hi! I’m having a hard time saving my input in the calendar. I’m using phonegap and whenever I press back, the event that I added is deleted/gone.

    Andddd, how do I add pre-defined events which users can delete? 😀

    Please help, newbie programmer here.

  • Chaeyoung Son

    allDay not working and resizing also. please help

  • KrystaL JunG

    allDay not working when making new event after refresh the event will show 12a New Event. it will start automatically in 12am not in allday and resizing not working in date and time. please help. it would be great if anyone will help. thanks

    • Sebbe

      Go to database and change allDay from false to true, you can also chans chans this:

      (in file ‘process.php’)

      if($type == ‘new’)

      {

      $startdate = $_POST[‘startdate’].’+’.$_POST[‘zone’];

      $title = $_POST[‘title’];

      $insert = mysqli_query($con,”INSERT INTO calendar(title, startdate, enddate, allDay) VALUES(‘$title’,’$startdate’,’$startdate’,’false’)”);

      $lastid = mysqli_insert_id($con);

      echo json_encode(array(‘status’=>’success’,’eventid’=>$lastid));

      }

      to:

      if($type == ‘new’)

      {

      $startdate = $_POST[‘startdate’].’+’.$_POST[‘zone’];

      $title = $_POST[‘title’];

      $insert = mysqli_query($con,”INSERT INTO calendar(title, startdate, enddate, allDay) VALUES(‘$title’,’$startdate’,’$startdate’,’true’)”);

      $lastid = mysqli_insert_id($con);

      echo json_encode(array(‘status’=>’success’,’eventid’=>$lastid));

      }

      • Darwin Talaman

        Thank You its helpful to me

  • Самые Интересные Видео

    Hi all, who have a problem for this error->”ReferenceError: update is not define”
    i fixed it.

    Add to index.html this:

    eventResize: function(event, delta, revertFunc) {

    console.log(event);

    var title = event.title;

    var end = event.end.format();

    var start = event.start.format();

    $.ajax({

    url: ‘process.php’,

    data: ‘type=resetdate&title=’+title+’&start=’+start+’&end=’+end+’&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);

    }

    });

    and to process.php this:
    I used PDO, if you dont use PDO need change to mysqli

    if($type == ‘update’)

    {

    $title = $_POST[‘title’];

    $startdate = $_POST[‘start’];

    $enddate = $_POST[‘end’];

    $eventid = $_POST[‘eventid’];

    ///////

    $db->exec(“UPDATE calendar SET title=’$title’, startdate = ‘$startdate’, enddate = ‘$enddate’ where id=’$eventid'”);

    if($db)

    echo json_encode(array(‘status’=>’success’));

    else

    echo json_encode(array(‘status’=>’failed’));

    }

    • Giacomo

      change the event resize with this:

      eventResize: function(event, delta, revertFunc) {

      console.log(event);

      var title = event.title;

      var end = event.end.format();

      var start = event.start.format();

      $.ajax({

      url: ‘process.php’,

      data: ‘type=resize&start=’+start+’&end=’+end+’&eventid=’+event.id,

      type: ‘POST’,

      dataType: ‘json’,

      success: function(response){

      if(response.status != ‘success’)

      revertFunc();

      },

      error: function(e){

      revertFunc();

      alert(‘Error processing your request: ‘+e.responseText);

      }

      });

      // update(title,start,end,event.id);

      },

      And insert this into the process.php file:

      if($type == ‘resize’)

      {

      $startdate = $_POST[‘start’];

      $enddate = $_POST[‘end’];

      $eventid = $_POST[‘eventid’];

      // $update = mysqli_query($con,”UPDATE calendar SET title=’$title’, startdate = ‘$startdate’, enddate = ‘$enddate’ where id=’$eventid'”);

      $sql_update = “UPDATE calendar SET startdate = ‘$startdate’, enddate = ‘$enddate’ where id=’$eventid'”;

      $update = $DB_con->query ( $sql_update );

      if($update)

      echo json_encode(array(‘status’=>’success’));

      else

      echo json_encode(array(‘status’=>’failed’));

      }

      I’m using PDO instead of mysqli but the process is the same. You need only to change library back to mysqli

  • Carlos Antonio García Aguilar

    HI..excellent work…but how i can store or set background-color and border-color of events using a colored external event???

  • Goran Dolenc

    Looks like a nice tutorial, to bad it is not working. At least not for me. I have setup the files localhost, but the calendar does not show on the website at all. Must be some JS error I guess. Anyone willing to set things up for me, I am willing to pay…

  • Jorge Romão

    Event “user creator” (var userCreator) not appear in Tooltip, when I drag (add) an event to a calendar. Appear the ID, TITLE, but not userCreator (field of database table)
    Only appears when I do the refresh page (calendar).
    My code are:

    $(‘#calendar’).fullCalendar({
    events: JSON.parse(json_events),

    eventReceive: function(event){
    var title = event.title;
    var start = event.start.format(“YYYY-MM-DD”);
    var prof = XPTO;

    $.ajax({
    url: fichProcessamento,
    data: ‘type=new&title=’+title+’&startdate=’+start+’&prof=’+prof,
    type: ‘POST’,
    dataType: ‘json’,
    success: function(response){
    event.id = response.eventid;
    $(‘#calendar’).fullCalendar(‘updateEvent’,event)
    }
    });
    },

    eventMouseover: function (event, jsEvent) {
    var xOffset = 0;
    var yOffset = 0;
    var userCreator = event.utilizador;
    tiptext = userCreator;
    $(“body”).append(“” + tiptext + “”);
    $(“#tooltip”)
    .css(“z-index”, 91000)
    .css(“position”, “absolute”)
    .css(“top”, ($(this).offset().top + $(this).outerHeight() + yOffset) + “px”)
    .css(“left”, ($(this).offset().left + xOffset) + “px”)
    .css(“background”, “rgba(255, 255, 204, 0.8)”)
    .fadeIn(400);
    },
    eventMouseout: function (event, jsEvent) {
    $(“#tooltip”).remove();
    },

  • Pablo

    Hi, this tutorial is very interesting for me, but I saw a bug in the resize of the event in the week view of the calendar, if you try to resize you will see that you cannot complete the operation. from console of firefox appears: Uncaught ReferenceError: update is not defined, refered to the function eventResize –> update(title,start,end,event.id);
    In the download folder there is the same problem.
    Waiting for your solution 😉

  • Marvin

    will this work even with codeigniter if i made little bit of changes on the adding editing and deleting of events ?

    • Yes this app does not directly deal with PHP but Json. So no worries.

  • PhoomTh

    Nice tutorial can i ask a little bit can make it responsive?

    • It should be quite easy to achieve only with CSS you could try it!

      I found this and this should help you http://bootsnipp.com/snippets/2pnpg

      • Nick

        I changed the css for #wrap to max-width:1100px; and #external-events to width: 15%; and #calendar to width: 80%; and it now seems to be responsive. No doubt it would be better to use the bootstrap classes but this was enough for me.

  • Ifedinma Eke

    i downloaded the file last week and it worked properly until yesterday. The calendar as a whole isn’t showing. Its running on a server and connected to a database.please help me

    • Yona-hime

      i have the same problem

      • Try downloading the file again. Import the sql file to ‘test’ database

        • Yona-hime

          i just found out this error in Index.html: Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help, check

          • Ifedinma Eke

            please can you share a link? thank you

          • Sakthivakeswaran

            I got the same error @haebak:disqus could you reply if you got any solution for this?

  • Ifedinma Eke

    hi, i have also downloaded the folder again and still nothing.

    • did you import the db.sql file to database? If not download the zip file again and find the sql

  • Yona-hime

    The calendar will not show in the index that was provided, except for the draggable events on the left side, how do I let it show? someone help

    • Check the browser console for any error. Did the calendar work properly without any modification?

      • Yona-hime

        There was no error but the calendar itself won’t show :/

        • did you import the db.sql file to the database?

          • Yona-hime

            Yes, i already have it in my database sir

          • in the config.php ‘test’ is the database name you need to double check the config file with your database name and credentials. I just downloaded a copy and tried which works for me.

          • Yona-hime

            Yes, it is connected successfully to the database but still the calendar in index.html won’t show, i don’t know what’s wrong with this though :/

  • Viper Tkd

    Hi, I copied your code, updating with you modifications written bellow and get this error:

    SyntaxError: function statement requires a name

    });eventReceive: function(event){

  • Yona-hime

    I have this problem “index.html:65 Uncaught ReferenceError: json_events is not defined”

    on this line of code : events: JSON.parse(json_events),
    How can this be solved?

  • Penelope

    What is the use of allDay ?

  • Vadim Serebrinskiy

    Hi i get an error such as :

    (index):62 Uncaught ReferenceError: json_events is not defined

    any thoughts on how i resolve this ?

    preceding this on the devloper tools it also says :

    https://code.jquery.com/jquery-2.1.1.min.js Failed to load resource: the server responded with a status of 500 (Internal Server Error)k.cors.a.crossDomain.send @ jquery-2.1.1.min.js:4
    (index):62 Uncaught ReferenceError: json_events is not defined

    i think the php is expecting xhr but we deal with json so it may be conflicting , not sure how to go about it

  • Manoj Fernando

    Thanks a lot!

  • Jason

    Cool, thank you very much!!!

  • Vishal Patel

    i need year view

  • Jeroen Witteman

    Great tutorial, thanx a lot!

  • Brian

    Hi there, great article.

    Downloaded and implemented no problem however, i have a rather large database of events and would like to be able to fetch them one month at a time instead of always loading all events for all time.

    Is there an easy way to go about this?

  • cesarkohl

    Really great and detailed tutorial. I read it along with the official documentation and could develop my application smoothly. Thanks!

  • yogurt

    how can i change the event id in the calendar?

  • AlbertaHomelessplan

    love this tutorial but I can’t seem to get it to work. I can drag an event, it’s added to database but I can’t name the event, can’t give it specific time and can’t delete – any suggestions?

  • Gerardo Gonzalez

    I’ve created few fc-event (external events) with different colours, but when I dropped them out into the calendar they are keeping original color. May I have an idea how to keep external event colour?.

  • Smart

    hi all, there seem to struggle. i can’t initialize the calendar. when i start it on the browser only, the trash can div appears. Any help please.

  • Smart

    hello people, how do i set up this, i imported the database but no calendar is initialized when on my browse.

  • Mar Unknown

    ill try to write the code but the calendar did not show on my browser please can you help me what are the problem and how to fix it?

  • Govo

    Would be great if you could change the alert to sweet alert , Have tried several ways to get sweet alert to work without success

  • sulanum

    Is this outdated? This is what i get :

    https://gyazo.com/6313288fcea533f64c43285978107e9f

  • Raf

    Very nice tutorial,
    Can I come delete event?

  • Andrej Bóka

    Excellent work, thanks.
    One question. Can use Your callendar to see and use only all day event and putting only one event to day? If yes, how?

  • Chandra Palusan

    hello i like your website…very2 good the tutorial…
    i have problem how to insert date using php, jquery, ajak i have simple source code..but i am can’t insert to database i hope you can help me
    //custom date editable
    $(‘.signup’).editable({
    type: ‘adate’,
    date: {
    //datepicker plugin options
    format: ‘yyyy/mm/dd’,
    viewformat: ‘yyyy/mm/dd’,
    weekStart: 1

    //,nativeUI: true//if true and browser support input[type=date], native browser control will be used
    //,format: ‘yyyy-mm-dd’,
    //viewformat: ‘yyyy-mm-dd’
    }
    })

  • Jonas grøndahl

    how would you handle recurring events? change the structure of the database?

  • Brito Alan LA

    Hello I want to block days so I can not create events those days for example block the day of my birthday so that nothing can be set that day and so random days of the year

  • Louie Melo

    I dont know why but i cant load the calendar it says Uncaught SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse ()
    at HTMLDocument. (index.php:62)
    at j (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at Function.ready (jquery.min.js:2)
    at HTMLDocument.I (jquery.min.js:2)

    Can somebody help me please?

  • yash

    I tried using this code it only shows a trash bar and letters xx. Can somebody help ?

  • Nick

    Excellent tutorial! What is the purpose of x which appears after the calendar please?

  • Charles Coiffier

    Hello, good tutorial ! I’ve got just one problem, I try to calcul the moment.duration between start and end and there is always a differnece of 300 mnutes (5 hours) with the reallity… I think it must be a problem of UTC but I can’t find the solution.

  • Виталий

    Author you test self code? Your code dont worked.

    • Neil

      You’re right

  • Виталий

    You use – eventReceive: function(event) why? Dont worked.
    fullcalendar use – select: function

  • Hafedh Boukthir

    Hello, How can I integrate this crud calendar with Codeigniter 3.0 ?
    Thank you in advance

  • ianhaneyit

    Hi, I want to use this in a clients new site I am building, can the add events be restricted to just a admin side with a login system so visitors on the front end cannot add events

  • jojo

    how do i add a variable?

  • bombam Bb

    oh thx man

  • Faruk Yetkin

    good job bro, thx for sharing..

    • Rebecca

      have you got it work? i am still struggling on how to display the calendar…

      • Neil

        Have you? I can’t display the calendar.

  • Mahmoud Sabry

    is it possible to add another events source that is not editable ?

  • Nirav

    How to block certain dates in full calendar?

Do you wan't to get notified?

I will not spam your inbox. I will only send email whenever I publish a new article or to share information about technology

You have Successfully Subscribed!