HighChart using AJAX, Codeigniter

It is known that high chart 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 minimum and maximum temperatures 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 high chart. 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.

Recommended Reading:

Prerequisites

PHP 5.5 – 7.4.3, MySQL 5.5 – 8.0.17, Apache HTTP server 2.2, Codeigniter 2.1.4 – 3.1.11, AJAX, jQuery 1.9.1 – 3.5.1

Project Directory

It’s assumed that you have setup Apache, PHP and Codeigniter in Windows system. Now I will create a project root directory called codeIgniter-ajax-highchart under the Apache server’s htdocs folder.

Now move all the directories and files from CodeIgniter framework into codeIgniter-ajax-highchart directory.

I may not mention the project root directory in subsequent sections and I will assume that I am talking with respect to the project root directory.

Asset Folder

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

MySQL Table

I am creating a table and inserting some sample data to test the application right away once code implementation part is done.

If you are using MySQL version less than 8 then you need to use charset utf-8 and collate utf8_unicode_ci.

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

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

Database Configuration

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

Make sure to update the database configurations according to your values.

If you are using MySQL version less than 8 then you need to use char_set utf-8 and dbcollat utf8_unicode_ci.

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => 'root',
	'database' => 'roytuts',
	'dbdriver' => 'mysqli',
        ...
	'char_set' => 'utf8mb4',
	'dbcollat' => 'utf8mb4_unicode_ci',
        ...
);

Auto Configurations

Modify the autoload.php file at location application/config/ folder to autoload certain things which will be used throughout the application.

$autoload['libraries'] = array('database');
$autoload['helper'] = array('url', 'file');

Model

Create a model, which will give you the data for the high 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 */

Controller

Now create one controller called HighChart in the file application/controller/HighChart.php with below code.

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

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

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

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

    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 */

Route Configuration

Now modify the application/config/routes.php file to configure the routing for your controller instead of default controller.

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

View File

Next create a view with the following code. In this file I have created date picker so that you can easily change the default date displayed on the UI. By default today’s date is displayed on the page.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8"/>
        <title>HighChart using AJAX, Codeigniter 3.1.11</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 base_url(); ?>assets/js/jquery-1.9.1.min.js"></script>
        <script type='text/javascript' src="<?php echo base_url(); ?>assets/js/jquery-migrate-1.2.1.js"></script>-->
		<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
        <!--<script type='text/javascript' src="<?php echo base_url(); ?>assets/js/jquery-ui-1.10.3-custom.min.js"></script>-->
		<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
        <script type='text/javascript' src='<?php echo base_url(); ?>assets/js/sugar.min.js'></script>
        <script type='text/javascript' src='<?php echo base_url(); ?>assets/js/highcharts.js'></script>
        <script type='text/javascript' src='<?php echo base_url(); ?>assets/js/highcharts-more.js'></script>
        <script type='text/javascript' src='<?php echo base_url(); ?>assets/js/exporting.js'></script>
        <script type='text/javascript' src='<?php echo base_url(); ?>assets/js/script.js'></script>
        <script type='text/javascript' src='<?php echo base_url(); ?>assets/js/daterangepicker.js'></script>
    </head>
    <body>
        <div style="margin: 10px 0 0 10px;">
            <h3>Highchart Example using AJAX, Codeigniter 3.1.11</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>

The chart data displayed for this example is from 29th May 2020 to 27th May 2020 dates.

Testing the Application

Make sure your HTTP Apache server is running. Now access the URL http://localhost/codeIgniter-ajax-highchart/ in the browser. By default you won’t see any data on the chart because for current date there is no data available. For date range 29th May 2020 to 27th June 2020 you will see the following data on the high chart. You can also check what is minimum and maximum temperature for a particular day by mouse hover on the chart.

ajax jquery codeigniter hichchart

Source Code

Download

2 thoughts on “HighChart using AJAX, Codeigniter

  1. 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.

Leave a Reply

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