This tutorial shows how to create an AJAX monthly event calendar in JavaScript using the monthly HTML5 event calendar from DayPilot Pro for JavaScript package. It includes a sample PHP project with an SQLite database. The event calendar supports common drag and drop operations (event creating, moving and resizing) and is styled using a CSS theme.

Requirements

  • PHP 5

See Also

Features

  • Monthly event calendar
  • Highlighting weekends
  • Full CSS styling
  • CSS theme support
  • Loading events from the server using AJAX calls
  • Drag and drop event creating
  • Drag and drop event moving
  • Drag and drop event resizing
  • Sample PHP server backend
  • Sample SQLite database
  • HTML5
  • Includes a trial version of DayPilot Pro for JavaScript (see License below)

License

Licensed for testing and evaluation purposes. Please see the license agreement included in the sample project. You can use the source code of the tutorial if you are a licensed user of DayPilot Pro for JavaScript. Buy a license.

Setup

Include the following files from the DayPilot Pro for JavaScript package:

  • Include daypilot-all.min.js
  • The default CSS theme is built in so you don't need to include a separate stylesheet file.
<script src="js/daypilot/daypilot-all.min.js" type="text/javascript"></script>

Placeholder Div

The monthly event calendar requires a placeholder div on the page.

<div id="dp"></div>

JavaScript Initialization Code

The monthly event calendar widget must be created using DayPilot.Month class.

<script type="text/javascript">
  var dp = DayPilot.Month("dp");
  dp.init();
</script>

This will create the monthly calendar using the placeholder div.

CSS Theme

There are several standard CSS themes included in DayPilot Pro for JavaScript:

  • month_white
  • month_green
  • month_blue
  • month_transparent

We will we the default CSS theme. You can switch to a custom CSS theme using .theme property:

<script type="text/javascript">
  var dp = DayPilot.Month("dp"); dp.theme = "month_white";
  dp.init();
</script>

You can also design your own CSS theme using the online theme designer.

Loading Events

The monthly calendar events can be loaded using .events.add() method.

The sample loadEvents methods using jQuery to make the AJAX call:

<script type="text/javascript">
  var dp = DayPilot.Month("dp");
  dp.init();

  loadEvents();

  function loadEvents() {
    $.post("backend_events.php", 
      function(data) {
        for (var i = 0; i < data.length; i++) {
          var e = new DayPilot.Event(data[i]);
          dp.events.add(e);
        }
      }
    );
  }
</script>

You can also load the events all at once by filling the .events.list array:

function loadEvents() {
  $.post("backend_events.php", 
      function(data) {
          dp.events.list = data;
          dp.update();
      }
  );
}

backend_events.php

<?php
require_once '_db.php';
    
$result = $db->query('SELECT * FROM events');

class Event {}
$events = array();

foreach($result as $row) {
  $e = new Event();
  $e->id = $row['id'];
  $e->text = $row['name'];
  $e->start = $row['start'];
  $e->end = $row['end'];
  $events[] = $e;
}

header('Content-Type: application/json');
echo json_encode($events);

?>

Highlighting Weekends

You can customize the day cells of the monthly event calendar using onBeforeCellRender event.

<script type="text/javascript">
  var dp = DayPilot.Month("dp");
  dp.onBeforeCellRender = function(args) {
      if (args.cell.start.getDayOfWeek() === 6 || args.cell.start.getDayOfWeek() === 0) {
          args.cell.backColor = "#eee";
      }
  };
  dp.init();
</script>

Moving Calendar Events using Drag and Drop

Drag and drop moving is enabled for the calendar events by default. The drag and drop event moving invokes two events:

  • onEventMove (after the event is dropped at the target location but before the event is actually moved; it is possible to cancel the move by calling args.preventDefault() here)
  • onEventMoved (after the update is finished)

We will use onEventMoved to notify the PHP server backend about the update.

After the server response is received we will display a message to the user using .message() method.

<script type="text/javascript">
  var dp = DayPilot.Month("dp");
  dp.onEventMoved = function (args) {
      $.post("backend_move.php",
          {
              id: args.e.id(),
              start: args.newStart.toString(),
              end: args.newEnd.toString()
          },
          function(data) {
              dp.message("Moved: " + data.message);
          }
      );        
  };
  dp.init();
</script>

backend_move.php

<?php
require_once '_db.php';

$stmt = $db->prepare("UPDATE events SET start = :start, end = :end WHERE id = :id");
$stmt->bindParam(':start', $_POST["start"]);
$stmt->bindParam(':end', $_POST["end"]);
$stmt->bindParam(':id', $_POST["id"]);
$stmt->execute();

class Result {}

$response = new Result();
$response->result = 'OK';
$response->message = 'Update successful';

header('Content-Type: application/json');
echo json_encode($response);

?>

Resizing Calendar Events using Drag and Drop

The monthly calendar event resizing work the same way as moving.

<script type="text/javascript">
  var dp = DayPilot.Month("dp");
  dp.onEventResized = function (args) {
      $.post("backend_move.php",
          {
              id: args.e.id(),
              start: args.newStart.toString(),
              end: args.newEnd.toString()
          },
          function(data) {
              dp.message("Moved: " + data.message);
          }
      );        
  };
  dp.init();
</script>

backend_resize.php

<?php
require_once '_db.php';

$stmt = $db->prepare("UPDATE events SET start = :start, end = :end WHERE id = :id");
$stmt->bindParam(':start', $_POST["start"]);
$stmt->bindParam(':end', $_POST["end"]);
$stmt->bindParam(':id', $_POST["id"]);
$stmt->execute();

class Result {}

$response = new Result();
$response->result = 'OK';
$response->message = 'Update successful';

header('Content-Type: application/json');
echo json_encode($response);

?>

Adding Calendar Events using Drag and Drop

It is possible to add new events by selecting a time range (by dragging a mouse). This action will fire onTimeRangeSelect and onTimeRangeSelected events.

We will use onTimeRangeSelected to display a simple built-in browser dialog and ask for the name of the new calendar event.

<script type="text/javascript">
  var dp = DayPilot.Month("dp");

  // event creating
  dp.onTimeRangeSelected = function (args) {
      var name = prompt("New event name:", "Event");
      dp.clearSelection();
      if (!name) return;

      $.post("backend_create.php", 
          {
              start: args.start.toString(),
              end: args.end.toString(),
              name: name
          }, 
          function(data) {
              var e = new DayPilot.Event({
                  start: args.start,
                  end: args.end,
                  id: data.id,
                  text: name
              });
              dp.events.add(e);

              dp.message(data.message);
          });
      };

  dp.init();
</script>

backend_create.php

<?php
require_once '_db.php';

$stmt = $db->prepare("INSERT INTO events (name, start, end, resource) VALUES (:name, :start, :end, :resource)");

$stmt->bindParam(':start', $_POST["start"]);
$stmt->bindParam(':end', $_POST["end"]);
$stmt->bindParam(':name', $_POST["name"]);
$stmt->execute();

class Result {}

$response = new Result();
$response->result = 'OK';
$response->message = 'Created with id: '.$db->lastInsertId();
$response->id = $db->lastInsertId();

header('Content-Type: application/json');
echo json_encode($response);

?>

Related Tutorials

HTML5 Scheduler for JavaScript/PHP

scheduler-javascript-php-html5-windows-8-css-theme.png

This tutorial show how to use DayPilot HTML5 scheduler (multiple resources on Y axis, time on X axis).

HTML5 Event Calendar for JavaScript/PHP

javascript-event-calendar-php-week.png

This tutorial shows how to use DayPilot HTML5 event calendar (day/week view with CSS themes and drag & drop support).