Amitav Roy

Blog on web and travel

Codeigniter jQuery graphs from PHP data

Posted on July 2019

Codeigniter jQuery graphs from PHP data

This time I will show you some UI goodies using my favourite jQuery. With highly interactive web applications, graphs are must for any application, and jQuery is just the right tool for this.

For example, let's assume you have a money application and you want to show a graph of spending in a year grouped by month. Well, a few years back a good looking table with the data month wise would have been awesome. But now, that’s old fashion.

So here I am working on how to use the data from PHP and show a jQuery super cool graph. There are a lot of libraries available for download that we can use and believe me implementing most of them are almost the same. It’s just the requirement on which you have to decide which one to use. In this example, I will be using jqBarGraph jquery plug-in. It is very easy and quite customizable. And the best part is, its only 5.1kb when minified. Check this link.

Codeigniter jQuery graphs from PHP data

From the framework point of view, I will have a site controller with only the index function. One model for the table from where I will be fetching the data, and last but not the least the view for the page. Well, that takes care of the MVC approach.

Here is the code for my site controller:

class Site extends CI_Controller {
    
  /**
   * The __construct function is called so that I don't have to load the model each and every time.
   * And any change while refactoring or something else would mean change in only one place.
   */
  function __construct() {
    parent::__construct();
    $this->load->model('data_model');
  }
    
  /**
   * This is the first method which get's executed when someone will go to the site section.
   */
  function index() {
    $data['year_graph'] = $this->data_model->get_data();
    $this->load->view('site_index',$data);
  }
}

Nothing fancy, it has an index function where I am passing the $data array to the view “site_index” and “year_graph” is the variable which I will get with the data inside the view. The “year_graph” data is coming from the model “data_model” model’s function get_data which for now simple returns all the entries from the table “year_data”.

Here is the code for the mode:

class Data_model extends CI_Model {
    
  function get_data() {
    $this->db->select();
    $query = $this->db->get('year_data');
      
    if ($query->num_rows > 0) {
      return $query->result();
    }
    else {
      return FALSE;
    }
  }
}

Now the most important part – the view:

<html>
  <head>
    <title>jQuery Ajax tutorial using Code Igniter Framework</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" src="<?php print base_url(); ?>/js/jqbargraph.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function () {
        var arrayOfPHPData = <?php echo json_encode($year_graph) ?>;
        arrayOfDataJS = new Array();
        $.each(arrayOfPHPData, function (i, elem) {
          arrayOfDataJS[i] = [parseInt(elem['count']),parseInt(elem['year'])];
        });
        console.log(arrayOfDataJS);
        $('#divForGraph').jqBarGraph({
          data: arrayOfDataJS,
          title: "This is the title and <strong>Bold</strong> is working",
          barSpace: 20,
          postfix: 'Year',
        });
      });
    </script>
  </head>
    
  <body>
 
<div id="wrapper">
 
<div id="divForGraph"></div>
 
    </div>
 
  </body>
</html>

So, here is what is going on inside the view: At line 4 and 5 I have added the js files which are required for this exercise. And then I have started a script tag where all the coding for the graph goes into. The whole thing should be inside the $ document.ready otherwise it will not work.

So, on line 8 is the arrayOfPHPData which got converted into json. After that I have build the “arrayOfDataJS” array which will be the final array which will be used to display the graphs.

Line 10 is where I assign each values to the new array from the json string through each() function.

Once that is done, I have done a console.log to check how the data is coming and whether is in correct format or not. Be sure to remove this when all the development is done.

Then from line 14 onwards the different settings for the graphs are explored. There are a few more which you can get from the site, but I have added almost all the major ones.

“divForGraph” is the div where all the graph data will be rendered. Here is my output:

Codeigniter jQuery graphs from PHP data