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:
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:
CREATE TABLE account( id INT(11) PRIMARY KEY AUTO_INCREMENT, year YEAR(4), purchase INT(11), sale INT(11), profit INT(11) )ENGINE=INNODB;
STEP 3. INSERT SOME DATA
Insert some data into the “account” table by executing the following query:
INSERT INTO account (year,purchase,sale,profit) VALUES ('2013','2000','3000','1000'), ('2014','4500','5000','500'), ('2015','3000','4500','1500'), ('2016','2000','3000','1000'), ('2017','2000','4000','2000'), ('2018','2200','3000','800'), ('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:
$autoload['libraries'] = array(); $autoload['helper'] = array();
Set to be like this:
$autoload['libraries'] = array('database'); $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:
$config['base_url'] = '';
And then set to be like this:
$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:
$active_group = 'default'; $query_builder = TRUE; $db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => '', 'password' => '', 'database' => '', 'dbdriver' => 'mysqli', 'dbprefix' => '', 'pconnect' => FALSE, 'db_debug' => (ENVIRONMENT !== 'production'), 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8', 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array(), 'save_queries' => TRUE );
And then Set to be like this:
$active_group = 'default'; $query_builder = TRUE; $db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'chart_db', 'dbdriver' => 'mysqli', 'dbprefix' => '', 'pconnect' => FALSE, 'db_debug' => (ENVIRONMENT !== 'production'), 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8', 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array(), 'save_queries' => TRUE );
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:
$route['default_controller'] = 'welcome';
And then set to be like this:
$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:
<?php class Chart_model extends CI_Model{ //get data from database function get_data(){ $this->db->select('year,purchase,sale,profit'); $result = $this->db->get('account'); return $result; } }
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:
<?php class Chart extends CI_Controller{ function __construct(){ parent::__construct(); //load chart_model from model $this->load->model('chart_model'); } function index(){ $data = $this->chart_model->get_data()->result(); $x['data'] = json_encode($data); $this->load->view('chart_view',$x); } }
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:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Chart using codeigniter and morris.js</title> <link rel="stylesheet" href="<?php echo base_url().'assets/css/morris.css'?>"> </head> <body> <h2>Chart using Codeigniter and Morris.js</h2> <div id="graph"></div> <script src="<?php echo base_url().'assets/js/jquery.min.js'?>"></script> <script src="<?php echo base_url().'assets/js/raphael-min.js'?>"></script> <script src="<?php echo base_url().'assets/js/morris.min.js'?>"></script> <script> Morris.Bar({ element: 'graph', data: <?php echo $data;?>, xkey: 'year', ykeys: ['purchase', 'sale', 'profit'], labels: ['Purchase', 'Sale', 'Profit'] }); </script> </body> </html>
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:
<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:
<script src="<?php echo base_url().'assets/js/jquery.min.js'?>"></script> <script src="<?php echo base_url().'assets/js/raphael-min.js'?>"></script> <script src="<?php echo base_url().'assets/js/morris.min.js'?>"></script>
To display a chart, we use the following code:
<script> Morris.Bar({ element: 'graph', data: <?php echo $data;?>, xkey: 'year', ykeys: ['purchase', 'sale', 'profit'], labels: ['Purchase', 'Sale', 'Profit'] }); </script>
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:
<div id="graph"></div>
STEP 9. TESTING
To do the test, please open your browser and type the following URL:
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:
<script> Morris.Bar({ element: 'graph', data: <?php echo $data;?>, xkey: 'year', ykeys: ['purchase', 'sale', 'profit'], labels: ['Purchase', 'Sale', 'Profit'] }); </script>
Change to be like this:
<script> Morris.Line({ element: 'graph', data: <?php echo $data;?>, xkey: 'year', ykeys: ['purchase', 'sale', 'profit'], labels: ['Purchase', 'Sale', 'Profit'] }); </script>
Then visit the following URL to see the changes:
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:
<script> Morris.Area({ element: 'graph', data: <?php echo $data;?>, xkey: 'year', ykeys: ['purchase', 'sale', 'profit'], labels: ['Purchase', 'Sale', 'Profit'] }); </script>
Then visit the following URL to see the changes:
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.
So, what are waiting for. Let's coding!
Download Source Code
Comments (8)
natasha, 11 January 2019 11:37 -
Thank you very much for this tutorial.
M Fikri, 29 April 2019 09:46 -
You are welcome
nurul, 23 April 2019 16:20 -
How to set the routes if my chart shown in admin dashboard. My admin dashboard is in file admin as (index.php or admindashboard) . Sorry for the broken english.
M Fikri, 29 April 2019 09:50 -
Hi Nurul,
There is no problem with that.
You just call the following url to run it: