How To Create Chart Using
Codeigniter and Morris.js
 SEPTEMBER 27, 2018
  Want to know how to create chart using codeigniter and morris.js?
  Then you are in the right place.
  Because today, I will share with you how to create chart using
 codeigniter and morris.js step by step.
  Let’s get start it.
  STEP 1. PREPARATION
  This is important!
  If you missed this step, it means you missed the whole of this tutorial.
  Good preparation will determine your success following this tutorial.
 The better your preparation, the more likely you will succeed in
 following this tutorial.
  Do not skip this step, though it feels complex.
 So, what do you need to prepare?
 Here’s the list:
 1. Codeigniter
 Codeigniter is the main php framework we will use in this tutorial. If
 you do not have it yet, please download it at the official
 website: www.codeigniter.com
 2. Jquery
 Jquery is a javascript library that serves to help make it easier to
 manipulate html elements.
 If you don't have it yet, please download it on the official
 website: www.jquery.com
 3. Morris.js
 Morris.js is a javascript library to make it easier to create good-
 looking charts.
 If you don't have it yet, please download it on the official
 website: http://morrisjs.github.io/morris.js/
  4. Raphael.js
  Morris.js require raphael.js, so, we need raphael.js.
  Please visit the following url to get raphael.js:
  https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js
  Then select all the codes (Ctrl +A) then copy and save with the
 name raphael-min.js.
  STEP 2. CREATE DATABASE AND
 TABLE
  Create a database named chart_db.
  To create a database, you could executing the following query:
1 CREATE DATABASE chart_db;
  Then create a table named "account" with the structure like the
 picture below:
 
  To create a table with a structure like the picture above, you could
 executing the following query:
1
 CREATE TABLE account(
2 id INT(11) PRIMARY KEY AUTO_INCREMENT,
3 year YEAR(4),
4 purchase INT(11),
5 sale INT(11),
 profit INT(11)
6
 )ENGINE=INNODB;
7
  STEP 3. INSERT SOME DATA
  Insert some data into the “account” table by executing the following
 query:
1 INSERT INTO account (year,purchase,sale,profit) VALUES
2 ('2013','2000','3000','1000'),
3 ('2014','4500','5000','500'),
4 ('2015','3000','4500','1500'),
5 ('2016','2000','3000','1000'),
 ('2017','2000','4000','2000'),
6
7 ('2018','2200','3000','800'),
8 ('2019','5000','7000','2000');
  The query above will input 7 records data into the ”account” table.
  Like the picture below:
  STEP 4. CODEIGNITER INSTALLATION
  Extract codeigniter that has been downloaded earlier to www folder
 (if you use wampserver) or htdocs (if you use XAMPP).
  Because I use wampserver. So, I extract it to c:/wamp/www/
  And then, rename codeigniter project to be chart.
  Like the picture below:
 Open the chart folder and the create new folder
 named "assets" parallel to the application and system folders, then
 create the css and js folder inside the assets folder.
 And then copy the morris.css file into the css folder and copy
 the jquery.min.js, morris.min.js, and raphael-min.js files into
 the js folder.
 Pay attention to the following picture for more details:
 STEP 5. CODEIGNITER
 CONFIGURATION
 Next step is the configuration on the codeigniter.
 Here are some files you need to configure:
 1. Autoload.php
 To configure the autoload.php, please open the folder:
 application/config/autoload.php
 like this:
 Open autoload.php using text editor like Notepad++ or Sublime Text.
  And then find the code below:
1 $autoload['libraries'] = array();
2 $autoload['helper'] = array();
  Set to be like this:
1 $autoload['libraries'] = array('database');
2 $autoload['helper'] = array('url');
  2. Config.php
  To configure the config.php, please open the folder:
  application/config/config.php
  like the following picture:
 
  Open config.php file using text editor, and then find the code below:
1 $config['base_url'] = '';
  And then set to be like this:
1 $config['base_url'] = 'http://localhost/chart/';
  3. Database.php
  To configure the database.php, please open the folder:
  application/config/database.php
  like the picture below:
 
  Open database.php file using text editor, and then find the code
 below:
1 $active_group = 'default';
2 $query_builder = TRUE;
4 $db['default'] = array(
5 'dsn' => '',
 'hostname' => 'localhost',
6
 'username' => '',
7
 'password' => '',
8
 'database' => '',
9
 'dbdriver' => 'mysqli',
10
 'dbprefix' => '',
11 'pconnect' => FALSE,
12 'db_debug' => (ENVIRONMENT !== 'production'),
13 'cache_on' => FALSE,
14 'cachedir' => '',
15 'char_set' => 'utf8',
16 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
17
 'encrypt' => FALSE,
18
 'compress' => FALSE,
19
 'stricton' => FALSE,
20
 'failover' => array(),
21 'save_queries' => TRUE
22 );
23
24
  And then Set to be like this:
1 $active_group = 'default';
 $query_builder = TRUE;
2
3
 $db['default'] = array(
4
 'dsn' => '',
5
 'hostname' => 'localhost',
6
 'username' => 'root',
7
 'password' => '',
8 'database' => 'chart_db',
9 'dbdriver' => 'mysqli',
10 'dbprefix' => '',
11 'pconnect' => FALSE,
12 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
13
 'cachedir' => '',
14
 'char_set' => 'utf8',
15
 'dbcollat' => 'utf8_general_ci',
16
 'swap_pre' => '',
17 'encrypt' => FALSE,
18 'compress' => FALSE,
19 'stricton' => FALSE,
20 'failover' => array(),
 'save_queries' => TRUE
21
 );
22
23
24
  4. Routes.php
  To configure the routes.php, please open the folder:
  application/config/routes.php
  Like the picture below:
 
  Open routes.php file using text editor, and then find the code below:
1 $route['default_controller'] = 'welcome';
  And then set to be like this:
1 $route['default_controller'] = 'chart';
 
  STEP 6. MODEL
  The Model represents your data structures. Typically your model
 classes will contain functions that help you retrieve, insert, and
 update information in your database.
  In this case we just need one model, that is Chart_model.php
  So, create a model file models/Chart_model.php by the following
 the code below:
1
 <?php
2
 class Chart_model extends CI_Model{
3
4 //get data from database
5 function get_data(){
6 $this->db->select('year,purchase,sale,profit');
7 $result = $this->db->get('account');
 return $result;
8
 }
9
10
 }
11
  In the Chart_model model above there is just one function, that
 function get_data().
  Function get_data() is used to display all data from the "account"
 table in the database.
  In this case, we only display fields: year, purchase, sale, and profit.
  STEP 7. CONTROLLER
  The Controller serves as an intermediary between the Model, the
 View, and any other resources needed to process the HTTP request
 and generate a web page.
  In this case we just need one controller, that is Chart.php
  So, create a controller file controllers/Chart.php by the following the
 code below:
1 <?php
2 class Chart extends CI_Controller{
3 function __construct(){
 parent::__construct();
4
 //load chart_model from model
5
 $this->load->model('chart_model');
6
 }
7
8
 function index(){
9
 $data = $this->chart_model->get_data()->result();
10 $x['data'] = json_encode($data);
11 $this->load->view('chart_view',$x);
12 }
13 }
14
  On the Chart controller above, there are two functions. Function
 __connstruct() and function index().
  Function __constrsuct() is used as a constructor, while
 the function index() is the function that is called when
 the Chart controller is run.
  In the function index(), we call the
 function get_data() from Chart_model model.
  Then encoded the output to be JSON object by using
 the json_encode method.
  Then load the view "chart_view" by bringing an array "data".
  STEP 8. VIEW
  The View is the information that is being presented to a user.
  A View will normally be a web page, but in CodeIgniter, a view can
 also be a page fragment like a header or footer. It can also be an
 RSS page, or any other type of “page”.
  In this case we just need one view, that is chart_view.php
  So, create a view file views/chart_view.php by the following the
 code below:
1
 <!DOCTYPE html>
2
 <html lang="en">
3
 <head>
4
 <meta charset="utf-8">
5 <title>Chart using codeigniter and morris.js</title>
6 <link rel="stylesheet" href="<?php echo base_url().'assets/css/morris.css'?>">
7 </head>
8 <body>
9 <h2>Chart using Codeigniter and Morris.js</h2>
10
 <div id="graph"></div>
11
12
 <script src="<?php echo base_url().'assets/js/jquery.min.js'?>"></script>
13
 <script src="<?php echo base_url().'assets/js/raphael-min.js'?>"></script>
14
 <script src="<?php echo base_url().'assets/js/morris.min.js'?>"></script>
15
 <script>
16 Morris.Bar({
17 element: 'graph',
18 data: <?php echo $data;?>,
19 xkey: 'year',
20 ykeys: ['purchase', 'sale', 'profit'],
 labels: ['Purchase', 'Sale', 'Profit']
21
 });
22
 </script>
23
 </body>
24
 </html>
25
26
  In the view chart_view, we call morris.css, jquery.min.js, raphael-
 min.js, and morris.min.js files.
  To call the morris.css file, we use the following code:
1 <link rel="stylesheet" href="<?php echo base_url().'assets/css/morris.css'?>">
  To call the jquery.min.js, raphael-min.js,
 and morris.min.js files, we use the following code:
1 <script src="<?php echo base_url().'assets/js/jquery.min.js'?>"></script>
2 <script src="<?php echo base_url().'assets/js/raphael-min.js'?>"></script>
3 <script src="<?php echo base_url().'assets/js/morris.min.js'?>"></script>
  To display a chart, we use the following code:
1
 <script>
2
 Morris.Bar({
3 element: 'graph',
4 data: <?php echo $data;?>,
5 xkey: 'year',
6 ykeys: ['purchase', 'sale', 'profit'],
 labels: ['Purchase', 'Sale', 'Profit']
7
 });
8
 </script>
9
  The above code will display a bar chart on the graph element. Where
 the graph is the ID of an HTML element where the chart wants to be
 displayed.
  In this case, I want to display the chart into a div tag that
 has id="graph" like the following code:
1 <div id="graph"></div>
  STEP 9. TESTING
  To do the test, please open your browser and type the following URL:
  http://localhost/chart/
  if it's running well, it will look like the following picture:
  Awesome right?
  You can also change the style from the chart above to a line
 chart or area chart.
  To change the style of chart, it's quite simple just change the Bar to
 be Line.
  Like this:
1
 <script>
2
 Morris.Bar({
3 element: 'graph',
4 data: <?php echo $data;?>,
5 xkey: 'year',
6 ykeys: ['purchase', 'sale', 'profit'],
 labels: ['Purchase', 'Sale', 'Profit']
7
 });
8
 </script>
9
  Change to be like this:
1
 <script>
2
 Morris.Line({
3 element: 'graph',
4 data: <?php echo $data;?>,
5 xkey: 'year',
6 ykeys: ['purchase', 'sale', 'profit'],
 labels: ['Purchase', 'Sale', 'Profit']
7
 });
8
 </script>
9
  Then visit the following URL to see the changes:
  http://localhost/chart/
  if it's running well, it will look like the following picture:
  Beside that, You can also change the style to Area chart just by
 changing Line to Area.
  Like this:
1
 <script>
2
 Morris.Area({
3 element: 'graph',
4 data: <?php echo $data;?>,
5 xkey: 'year',
6 ykeys: ['purchase', 'sale', 'profit'],
 labels: ['Purchase', 'Sale', 'Profit']
7
 });
8
 </script>
9
  Then visit the following URL to see the changes:
  http://localhost/chart/
 if it's running well, it will look like the following picture:
 That’s it!.
 CONCLUSION
 In today's tutorial is about how to create a chart with codeigniter and
 morris.js.
 In this tutorial, you have learned how to create charts with codeigniter
 and morris.js step by step.
 Not only that, you have also learned how to change the style of chart
 from bar chart to line chart and chart area.