We know that xchart 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://tenxer.github.io/xcharts/ for more information.

You can integrate xchart with any server side tehnology but here I will show you how to integrate xchart 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 xchart. 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.

Codeigniter Highchart

Final Output

Calendar – date picker

Codeigniter Hichchart example

When no record found for a date or date range

Codeigniter Hichchart example

When record(s) is/are found for a date or date range

Codeigniter Hichchart example

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

The below site_log table holds the information for visitor statistics

CREATE TABLE `site_log` (
`site_log_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`no_of_visits` int(10) unsigned NOT NULL,
`ip_address` varchar(20) NOT NULL,
`requested_url` tinytext NOT NULL,
`referer_page` tinytext NOT NULL,
`page_name` tinytext NOT NULL,
`query_string` tinytext NOT NULL,
`browser` tinytext NOT NULL,
`is_unique` tinyint(1) NOT NULL DEFAULT '0',
`access_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`site_log_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2425 DEFAULT CHARSET=utf8;

 

The below session table holds session information for each client

CREATE TABLE `session` (
`session_id` varchar(45) NOT NULL,
`ip_address` varchar(20) NOT NULL,
`user_agent` varchar(255) NOT NULL,
`last_activity` int(10) unsigned NOT NULL,
`user_data` text NOT NULL,
PRIMARY KEY (`session_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

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'] = 'blog';
$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. Modify the config.php file at location application/config/config.php. I am not using index.php file in URL so you can go through tutorial how to remove index.php from URL in Codeigniter

$config['index_page'] = '';
$config['encryption_key'] = '2d8+e6]K0?ocWp7&`K)>6Ky"|.x|%nuwafC~S/+6_mZI9/17y=sKKG.;Tt}k';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = TRUE;
$config['sess_encrypt_cookie'] = TRUE;
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'session';
$config['sess_match_ip'] = TRUE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;

 

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

assets_helper.php

<?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 5. Modify the config.php file at location application/config/autoload.php

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

 

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

<?php

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

/**
* Description of highchart_model
*
* @author https://www.roytuts.com
*/
class Highchart_model extends CI_Model {

private $site_log = 'site_log';

/**
* get chart data
*/
function get_chart_data_for_visits($start_date, $end_date) {
$sql = 'SELECT SUM(no_of_visits) total_visits, DATE(access_date) day_date
FROM ' . $this->site_log . '
WHERE DATE(access_date) >= ' . $this->db->escape($start_date) . '
AND DATE(access_date) <= ' . $this->db->escape($end_date) . '
GROUP BY DATE(access_date) ORDER BY DATE(access_date) DESC';
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
$data = array();
foreach ($query->result_array() as $key => $value) {
$data[$key]['label'] = $value['day_date'];
$data[$key]['value'] = $value['total_visits'];
}
return $data;
}
return NULL;
}

}

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

 

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

<?php

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

/**
*
* @author https://roytuts.com
*/
class Highchart extends CI_Controller {

function __construct() {
parent::__construct();
$this->load->model('highchart_model');
$this->load->library('form_validation');
}

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

function get_chart_data() {
if (isset($_POST['start']) AND isset($_POST['end'])) {
$start_date = $_POST['start'];
$end_date = $_POST['end'];
$results = $this->highchart_model->get_chart_data_for_visits($start_date, $end_date);
if ($results === NULL) {
echo json_encode('No record found');
} else {
echo json_encode($results);
}
} else {
echo json_encode('Date must be selected.');
}
}

}

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

 

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

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

Step 9. Next create a view with the following code

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Highchart example in Codeigniter </title>
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/charts/chart.css">
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/charts/xcharts.min.css">
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/charts/bootstrap.min.css">
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/daterangepicker.css">
<script src="<?php echo assets_url(); ?>assets/js/jquery-1.9.1.min.js"></script>
<script src="<?php echo assets_url(); ?>assets/js/jquery-migrate-1.2.1.js"></script>
<script 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/charts/d3.v2.js'></script>
<script type='text/javascript' src='<?php echo assets_url(); ?>assets/js/charts/sugar.min.js'></script>
<script type='text/javascript' src='<?php echo assets_url(); ?>assets/js/charts/xcharts.min.js'></script>
<script type='text/javascript' src='<?php echo assets_url(); ?>assets/js/charts/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>Codeigniter Highchart Example</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="placeholder">
<figure id="chart"></figure>
</div>
</div>
</body>
</html>

 

Step 10. Run the application.

You can download the sample data for table site_log

data

Please download all the files for css and js from here.

assets

Thanks for your reading. Please do not forget to leave a comment.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials | TwitterFacebook Google PlusLinkedin | Reddit | Email Me

5 thoughts on “Codeigniter XChart Example

Leave a Reply

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