Friday 8 November 2019

FullCalendar CRUD Operation in Codeigniter using Ajax



If you are using Codeigniter framework for your web development, then this tutorial will help you on topic like how to integrate FullCalendar with your existing Codeigniter project. By using this post, you can learn How to Save events in Mysql database using Codeigniter and display particular date event on that date with time by using FullCalendar plugin. Even you can also change event date and time also. If you want to remove or delete particular event from calendar then that operation you can perform with FullCalendar in Codeigniter.

For this all operation you have to use Ajax call when ever you have create, update, load and delete event with FullCalendar using Codeigniter and save data into Database. In short you can perform CRUD operations of FullCalendar with Codeigniter. So, if you are looking for tutorial on Basic CRUD (Create Read Update Delete) functionality on jQuery FullCalendar using Codeigniter, then this post will help you.

We will describe you how to implement Full Calendar library in Codeigniter 3 application using Ajax. We will show you step by step process for how to create event, how to define event time and how to save event data into Mysql database with FullCalendar using Ajax in Codeigniter framework.

Do you know FullCalendar is an Open source jQuery library for create event in Calendar and we can easily customize our event management. FullCalendar library has also provide drag and drop event and resize event also. Follow following steps for Build Event Calendar in Codeigniter using jQuery FullCalendar plugin with Ajax and Mysql database.





  • Create Database Table

  • Make Database Connection

  • Create Controller

  • Create Model

  • Create View File




Create Database Table


For any dynamic web application, we need to create database and in that we have make table. For this you have to run following SQL script in your Mysql database, it will make events table in your database.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `events`
--

CREATE TABLE `events` (
  `id` int(11) NOT NULL,
  `title` varchar(255) NOT NULL,
  `start_event` datetime NOT NULL,
  `end_event` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `events`
--

INSERT INTO `events` (`id`, `title`, `start_event`, `end_event`) VALUES
(1, 'Meeting with Mike', '2019-11-08 12:00:00', '2019-11-08 13:00:00'),
(4, 'Meeting with Mike', '2019-11-11 15:30:00', '2019-11-11 16:30:00');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `events`
--
ALTER TABLE `events`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `events`
--
ALTER TABLE `events`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;


Make Database Connection


Once you have create table in your database, then after you have to make database connection with your Codeigniter application. For this you have to open application/config/database.php file, and in this you have to define your Mysql database configuration, which you can see below.

application/config/database.php

<?php

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root',
 'password' => '',
 'database' => 'testing',
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => FALSE,
 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
 'cachedir' => '',
 'char_set' => 'utf8',
 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
 'encrypt' => FALSE,
 'compress' => FALSE,
 'stricton' => FALSE,
 'failover' => array(),
 'save_queries' => TRUE
);

?>


Create Controller


Codeigniter is MVC framework, so in this for handle http request we have to create Controller class. So, here we have create controller file under application/controllers folder. In this class we have make following method.

__construct() - This is magic method of this class. When new object of this class has been created then it will execute this block of code.

index() - This is root method of this class, and it has load "fullcalendar.php" view file in browser.

load() - This method has return all events data. This method will received Ajax request for fetch all events data, then in respose it has send events data in JSON string format.

insert() - This method has received ajax request for store new event data into Mysql database.

update() - This method has been used for update existing event data, for update data it has received ajax request.

delete() - This method has received Ajax request for delete or remove particular event.

application/controllers/FullCalendar.php

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Fullcalendar extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  $this->load->model('fullcalendar_model');
 }

 function index()
 {
  $this->load->view('fullcalendar');
 }

 function load()
 {
  $event_data = $this->fullcalendar_model->fetch_all_event();
  foreach($event_data->result_array() as $row)
  {
   $data[] = array(
    'id' => $row['id'],
    'title' => $row['title'],
    'start' => $row['start_event'],
    'end' => $row['end_event']
   );
  }
  echo json_encode($data);
 }

 function insert()
 {
  if($this->input->post('title'))
  {
   $data = array(
    'title'  => $this->input->post('title'),
    'start_event'=> $this->input->post('start'),
    'end_event' => $this->input->post('end')
   );
   $this->fullcalendar_model->insert_event($data);
  }
 }

 function update()
 {
  if($this->input->post('id'))
  {
   $data = array(
    'title'   => $this->input->post('title'),
    'start_event' => $this->input->post('start'),
    'end_event'  => $this->input->post('end')
   );

   $this->fullcalendar_model->update_event($data, $this->input->post('id'));
  }
 }

 function delete()
 {
  if($this->input->post('id'))
  {
   $this->fullcalendar_model->delete_event($this->input->post('id'));
  }
 }

}

?>


Create Model


In Codeigniter framework, Model class has been used to perform database related operation. Here model class has been store in application/models folder. In this class we have to make following method.

fetch_all_event() - This method has fetch all event data from mysql table, and send that data to controller.

insert_event($data) - This is another method of model class which has been perform insert data operation. In short, this method has been used for insert new event data into mysql database.

update_event($data, $id) - For update existing data of event, here we have use this update_event() method, in this method there is two argument, first is $data is the event data, which we want to update into database, and $id is the id of event which we want to update.

delete_event($id) - For perform delete or remove event data opertion will done by this method. This method has one $id as argument which is id of particular event, which we want to remove from database.

application/models/Fullcalendar_model.php

<?php

class Fullcalendar_model extends CI_Model
{
 function fetch_all_event(){
  $this->db->order_by('id');
  return $this->db->get('events');
 }

 function insert_event($data)
 {
  $this->db->insert('events', $data);
 }

 function update_event($data, $id)
 {
  $this->db->where('id', $id);
  $this->db->update('events', $data);
 }

 function delete_event($id)
 {
  $this->db->where('id', $id);
  $this->db->delete('events');
 }
}

?>


Create View File


For display dynamic HTML output in browser, here in Codeigniter framwork we have use view file. View file has been store under application/views folder. Here we have create fullcalendar.php file under views folder.

For use jQuery FullCalendar plugin, we have to use following library link in our html file.


<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>


Here first we have to define one division tag on which we want to initialize FullCalendar plugin.


<div id="calendar"></div>


For initialize FullCalendar plugin on division tag with "calendar". We have to write following jquery code.


var calendar = $('#calendar').fullCalendar()


application/views/fullcalendar.php

<!DOCTYPE html>
<html>
<head>
    <title>Jquery FullCalendar Integration with Codeigniter using Ajax</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>
    <script>
    $(document).ready(function(){
        var calendar = $('#calendar').fullCalendar({
            editable:true,
            header:{
                left:'prev,next today',
                center:'title',
                right:'month,agendaWeek,agendaDay'
            },
            events:"<?php echo base_url(); ?>fullcalendar/load",
            selectable:true,
            selectHelper:true,
            select:function(start, end, allDay)
            {
                var title = prompt("Enter Event Title");
                if(title)
                {
                    var start = $.fullCalendar.formatDate(start, "Y-MM-DD HH:mm:ss");
                    var end = $.fullCalendar.formatDate(end, "Y-MM-DD HH:mm:ss");
                    $.ajax({
                        url:"<?php echo base_url(); ?>fullcalendar/insert",
                        type:"POST",
                        data:{title:title, start:start, end:end},
                        success:function()
                        {
                            calendar.fullCalendar('refetchEvents');
                            alert("Added Successfully");
                        }
                    })
                }
            },
            editable:true,
            eventResize:function(event)
            {
                var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss");
                var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");

                var title = event.title;

                var id = event.id;

                $.ajax({
                    url:"<?php echo base_url(); ?>fullcalendar/update",
                    type:"POST",
                    data:{title:title, start:start, end:end, id:id},
                    success:function()
                    {
                        calendar.fullCalendar('refetchEvents');
                        alert("Event Update");
                    }
                })
            },
            eventDrop:function(event)
            {
                var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD HH:mm:ss");
                //alert(start);
                var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD HH:mm:ss");
                //alert(end);
                var title = event.title;
                var id = event.id;
                $.ajax({
                    url:"<?php echo base_url(); ?>fullcalendar/update",
                    type:"POST",
                    data:{title:title, start:start, end:end, id:id},
                    success:function()
                    {
                        calendar.fullCalendar('refetchEvents');
                        alert("Event Updated");
                    }
                })
            },
            eventClick:function(event)
            {
                if(confirm("Are you sure you want to remove it?"))
                {
                    var id = event.id;
                    $.ajax({
                        url:"<?php echo base_url(); ?>fullcalendar/delete",
                        type:"POST",
                        data:{id:id},
                        success:function()
                        {
                            calendar.fullCalendar('refetchEvents');
                            alert('Event Removed');
                        }
                    })
                }
            }
        });
    });
             
    </script>
</head>
    <body>
        <br />
        <h2 align="center"><a href="#">Jquery FullCalendar Integration with Codeigniter using Ajax</a></h2>
        <br />
        <div class="container">
            <div id="calendar"></div>
        </div>
    </body>
</html>


So, here all steps done and by using this above step you can easily use jQuery FullCalendar plugin with Codeigniter framework using Ajax. If you face any difficulty in integrating FullCalendar plugin with Codeigniter framework, then you can also find video tutorial of this post also, which you can find above of this post. And lastly, If you want to get source code zip file of Codeigniter FullCalendar example, so by click on below link you can also get zip file of Basic Crud in FullCalendar with Codeigniter using Ajax.





13 comments:

  1. how can we make this work when touching ( not using mouse ) . thanks

    ReplyDelete
  2. Need some help please.
    I'm getting
    GET http://localhost/tutorial/codeigniter/index.php/fullcalendar/load?start=2019-12-01&end=2020-01-12&_=1577822901446 404 (Not Found) jquery.min.j

    and also when i try to post an event.
    jquery.min.js:4 POST http://localhost/tutorial/codeigniter/fullcalendar/insert 404 (Not Found)

    I'm very familiar with codeigniter but im stumped.

    Thank You
    Mickey (Canada)

    ReplyDelete
  3. Thanks for your codes it helps me a lot to learn more about this scheduling system but I have a problem I was not able to design it because i can't find where to design but the code you provide is working properly..

    hoping for your kind response thank you..

    ReplyDelete
  4. Can the same code when written in Laravel work

    ReplyDelete
  5. how to add more than one event in same date ?

    ReplyDelete
  6. I already displayed the calendar but when I tried make an event, there's nothing happened, there's no event shows/made in calendar. I followed all the instructions. How to fix this? Thanks in advance.

    ReplyDelete
  7. $(...).fullCalendar is not a function

    ReplyDelete
  8. Object not found!
    The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.

    If you think this is a server error, please contact the webmaster.

    Error 404
    localhost
    Apache/2.4.41 (Win64) OpenSSL/1.1.1c PHP/7.4.1

    ReplyDelete