We know that highchart basically displays different statistical data on different chart types such as column chart, bar chart, line chart, pie chart etc. You can have a look at the URL http://www.highcharts.com/ for more information.

You can integrate highchart with any server side tehnology but here I will show you how to integrate highchart with Codeigniter framework. This tutorial shows step by step so that we can understand how it happens. It displays the data for site visitors log in line chart. I have also put a calendar for date-picker so that you can pick a custom range of dates and get the visitor statistics in highchart. The calendar has more features like you can select Yesterday, Last One week, Last One month etc. On mouse hover on the line chart you can see the visitors count on a particular date.

If you have any query please feel free to leave a comment.

Prerequisites

Knowledge of PHP & Codeigniter, jQuery and AJAX
MySQL 5.x
Apache HTTP server 2.2
Codeigniter 2.1.4

Assets folder structure

You need to create assets folder in parallel to application folder for putting all asset files such as js, css, images etc.

Assets Directory Structure

Final Output

HighChart using AJAX, Codeigniter

Step 1. First thing is we need to create database table

CREATE TABLE `temperature` (
  `temp_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `temp_date` datetime NOT NULL,
  `temp_min` float NOT NULL,
  `temp_max` float NOT NULL,
  PRIMARY KEY (`temp_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

Dump some data into datatbase table

insert  into `temperature`(`temp_id`,`temp_date`,`temp_min`,`temp_max`) values 
(1,'2015-06-01 11:32:43',28,35),
(2,'2015-06-02 11:33:06',25,39),
(3,'2015-06-03 11:33:17',26,40),
(4,'2015-06-04 11:33:27',22,33),
(5,'2015-06-05 11:33:42',21,34),
(6,'2015-06-06 11:33:51',25.6,38.4),
(7,'2015-06-07 11:34:03',20.9,35.6),
(8,'2015-06-08 11:41:02',21.5,39.5),
(9,'2015-06-09 11:41:30',20.5,39.7),
(10,'2015-06-10 11:41:41',24,38.9),
(11,'2015-06-11 11:41:53',23,38),
(12,'2015-06-12 11:42:04',23.5,39.7),
(13,'2015-06-13 11:42:18',22.6,37.9),
(14,'2015-06-14 11:42:28',25,40.5),
(15,'2015-06-15 11:42:38',23.1,41),
(16,'2015-06-16 11:42:49',27,42),
(17,'2015-06-17 11:43:01',26,40.6);

Step 2. Once you have codeigniter framework setup in place then configure database settings at location application/config/database.php

$active_group = 'default';
$active_record = TRUE;

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'cdcol';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

Step 3. Create a assets helper file which gives us the URL for different assets like css, js etc.

<?php

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

function assets_url() {
    return base_url();
}

/* End of file assets_helper.php */
/* Location: ./application/helpers/assets_helper.php */

Step 4. Modify the autoload.php file at location application/config/autoload.php

$autoload['libraries'] = array('database');

$autoload['helper'] = array('url', 'file', 'assets', 'text', 'form');

Step 5. Create a model which will give us the data for the chart under application/models/highchartmodel.php. The below model file is pretty simple.

<?php

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

/**
 * Description of highchartmodel
 *
 * @author https://roytuts.com
 */
class HighChartModel extends CI_Model {

    private $temperature = 'temperature';

    function __construct() {
        
    }

    function get_chart_data($start_date, $end_date) {
        $sql = 'SELECT * 
                FROM ' . $this->temperature . '
		WHERE DATE(temp_date)>=' . $this->db->escape($start_date) .
                ' AND DATE(temp_date)<=' . $this->db->escape($end_date);
        $query = $this->db->query($sql);
        $results = $query->result();
        return $results;
    }

}

/* End of file highchartmodel.php */
/* Location: ./application/models/highchartmodel.php */

Step 6. Now create one controller called Highchart under application/controller/highchart.php with below code

<?php

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

/**
 * Description of highchart
 *
 * @author https://www.roytuts.com
 */
class HighChart extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('highchartmodel', 'chart');
    }

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

    public function get_chart_data() {
        if (isset($_POST['start']) AND isset($_POST['end'])) {
            $start_date = $_POST['start'];
            $end_date = $_POST['end'];
            $results = $this->chart->get_chart_data($start_date, $end_date);
            if ($results === NULL) {
                echo json_encode('No record found');
            } else {
                $json = '[';
                $counter = 1;
                foreach ($results as $result) {
                    $json .= '[';
                    $json .= strtotime($result->temp_date);
                    $json .= ',';
                    $json .= $result->temp_min;
                    $json .= ',';
                    $json .= $result->temp_max;
                    $json .= ']';
                    if ($counter < count($results)) {
                        $json .= ',';
                    }
                    $counter++;
                }
                $json .= ']';
                echo $json;
            }
        } else {
            echo json_encode('Date must be selected.');
        }
    }

}

/* End of file highchart.php */
/* Location: ./application/controllers/highchart.php */

Step 7. Now modify the application/config/routes.php file as follows

$route['default_controller'] = "highchart";

Step 8. Next create a view with the following code

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8"/>
        <title>HighChart using AJAX, Codeigniter</title>
        <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/bootstrap.min.css">
        <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/daterangepicker.css">
        <script type='text/javascript' src="<?php echo assets_url(); ?>assets/js/jquery-1.9.1.min.js"></script>
        <script type='text/javascript' src="<?php echo assets_url(); ?>assets/js/jquery-migrate-1.2.1.js"></script>
        <script type='text/javascript' src="<?php echo assets_url(); ?>assets/js/jquery-ui-1.10.3-custom.min.js"></script>        
        <script type='text/javascript' src='<?php echo assets_url(); ?>assets/js/sugar.min.js'></script>
        <script type='text/javascript' src='<?php echo assets_url(); ?>assets/js/highcharts.js'></script>
        <script type='text/javascript' src='<?php echo assets_url(); ?>assets/js/highcharts-more.js'></script>
        <script type='text/javascript' src='<?php echo assets_url(); ?>assets/js/exporting.js'></script>
        <script type='text/javascript' src='<?php echo assets_url(); ?>assets/js/script.js'></script>
        <script type='text/javascript' src='<?php echo assets_url(); ?>assets/js/daterangepicker.js'></script>
    </head>
    <body>
        <div style="margin: 10px 0 0 10px;">
            <h3>Highchart Example using AJAX, Codeigniter</h3>
            <form class="form-horizontal">
                <fieldset>
                    <div class="input-prepend">
                        <span class="add-on"><i class="icon-calendar"></i> </span> <input
                            type="text" name="range" id="range" />
                    </div>
                </fieldset>
            </form>
            <div id="msg"></div>
            <div id="chart"></div>
        </div>
    </body>
</html>

Step 9. Download the assets directory and put it under project root directory

assets

Step 10. Run the application.

That’s all. Thanks for reading.

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

16 thoughts on “HighChart using AJAX, Codeigniter

    1. The ‘chart’ is the alias for ‘highchartmodel’. If you want you could also use the model name ‘highchartmodel’ without using alias, i.e., $this->load->model(‘highchartmodel’);

  1. When i use Highcharts then my Datatable(jQuery datatable) lost his functionality.. in ci..
    Please help me..

  2. Hey discussion – I am thankful for the analysis , Does anyone know if my assistant would be able to acquire a blank a form form to fill out ?

  3. I followed the same step but I had not the same resultat nothing is showing just the calendar tools is displayed

      1. Is what I have to modify in the code of viewer to display the data of table I inform you that I am beginner in develepement

        1. The dummy data which attached to this tutorial are very old. so if everything is fine and you want data on the chart then you have to populate tables or select date ranges which fall between dummy data set date ranges.

  4. hey i didn’t found how to load value in your ajax in script.js . Can yo share script.js or jquery/ajax to call controller get_chart_data.

  5. i have updated the dummy data with curent date and following all the step including assets file, but the chart still not showing. Can you help me ?

Leave a Reply

Your email address will not be published. Required fields are marked *