Amitav Roy

Blog on web and travel

Codeigniter jQuery graphs from PHP data

Posted on 7 Feb 2012 by Amitav Roy

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.

Graph library in jQuery

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:

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:

Now the most important part – the view:

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:

Graph data in jQuery