Tutorial: HTML5 Gantt Chart (JavaScript/PHP)

This tutorial shows how to create an HTML5 Gantt chart using DayPilot Pro for JavaScript. PHP project with source code available for download.
Feb 5, 2015
html5 gantt chart

Features

  • HTML5 Gantt chart
  • CSS3 theme
  • Inline task creating
  • Drag and drop task moving
  • Drag and drop task resizing
  • Task hierarchy (task groups)
  • Task progress bar (percent complete)
  • Custom columns with additional information (task name, duration)
  • Milestone support
  • Task editing using a modal dialog
  • Fast AJAX updates

Source code of the tutorial is available for download.

Example: Loading Gantt Task Data from the Database

html5-gantt-chart-task-hierarchy.png

We will use jQuery to load the task data from the server side.

<script type="text/javascript">
  var dp = new DayPilot.Gantt("dp");
  dp.startDate = "2015-01-01";
  dp.days = 31;
  dp.init();

  loadTasks();

  function loadTasks() {
      $.post("backend_tasks.php", function(data) {
          dp.tasks.list = data;
          dp.update();
      });
  }

</script>

The backend_tasks.php script returns a JSON array structure with the task properties. The task children are stored in the "children" property.

<?php
require_once '_db.php';

class Task {}

$result = tasklist($db, db_get_tasks(null));

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

function tasklist($db, $items) {
    $result = array();

    foreach($items as $item) {
      $r = new Task();

      // rows
      $r->id = $item['id'];
      $r->text = $item['name'];
      $r->start = $item['start'];
      $r->end = $item['end'];
      
      $parent = $r->id;
      
      $children = db_get_tasks($parent);
      
      if (!empty($children)) {
          $r->children = tasklist($db, $children);
      }

      $result[] = $r;
    }
    return $result;
}
?>

The db_get_tasks() function is defined in _db.php:

function db_get_tasks($parent) {
    global $db;
    
    $str = 'SELECT * FROM task WHERE parent_id = :parent ORDER BY ordinal, ordinal_priority desc';
    if ($parent == null) {
        $str = str_replace("= :parent", "is null", $str);
        $stmt = $db->prepare($str);
    }
    else {
        $stmt = $db->prepare($str);
        $stmt->bindParam(':parent', $parent);
    }
    
    $stmt->execute();
    return $stmt->fetchAll();
}

Sample JSON data:

[
  {
    "id":"1",
    "text":"Task 1",
    "start":"2015-01-02T00:00:00",
    "end":"2015-01-04T00:00:00"
  },
  {
    "id":"6",
    "text":"Task 2",
    "start":"2015-01-04",
    "end":"2015-01-06"
  },
  {
    "id":"3",
    "text":"Task 3",
    "start":"2015-01-01",
    "end":"2015-01-02"
    "children":[
      {
        "id":"5",
        "text":"Sub-Task 3.1",
        "start":"2015-01-06",
        "end":"2015-01-11"
      }
    ]
  }
]

DayPilot for JavaScript, ASP.NET WebForms, ASP.NET MVC, Java