Advertisement
  1. Code
  2. PHP
  3. CodeIgniter

Build Ajax Data Grids with CodeIgniter and jQuery

Scroll to top

In this lesson, we will create a CodeIgniter library that allows us to generate data grids automatically for managing any database table. I'll explain each step required to create this class; so you'll likely learn some new OOP techniques/concepts in the process!

As a bonus, we'll proceed to write some jQuery code that will enable a user to update the data grid's content without having to wait for a page refresh.


Please Note...

This tutorial assumes that you have a modest understanding of the CodeIgniter and jQuery frameworks.

What is a Data Grid?

A datagrid is a table that displays the contents of a database or table along with sorting controls.

A datagrid is a table that displays the contents of a database or table along with sorting controls. In this tutorial, we will be tasked with providing this functionality, but also saving the user from waiting for the page to refresh each time an operation is performed. Thanks to jQuery, this will be a fairly simple task!

What about the users who don't have Javascript enabled? Don't worry, we'll compensate for them as well!


Step 1: Build a Data Grid Generator Class

We want to build a tool that will enable us to create datagrids dynamically for any database table that we have. This means the code is not tied up to any specific table structure, and, thus, is independent on the data itself. All the coder (the developer who uses our class) must know is the name of the table to be transformed into a grid and the primary key for that table. Here is the preface of the class that we will be developing for the most part of this tutorial:

1
<?php
2
class Datagrid{
3
	private $hide_pk_col = true;
4
	private $hide_cols = array();
5
	private $tbl_name = '';
6
	private $pk_col	= '';
7
	private $headings = array();
8
	private $tbl_fields = array();
9
}
10
?>

The Datagrid Class could well be added to the application/library folder, but we are going to add it as a helper to the CodeIgniter framework. Why? Because loading libraries doesn't allow us to pass arguments to the class' constructor, thus loading it as a helper will solve the problem. This point will make more sense for you when we have finished writing the constructor.

The Class' Constructor Method

1
public function __construct($tbl_name, $pk_col = 'id'){
2
	$this->CI =& get_instance();
3
	$this->CI->load->database();
4
	$this->tbl_fields = $this->CI->db->list_fields($tbl_name);
5
	if(!in_array($pk_col,$this->tbl_fields)){
6
		throw new Exception("Primary key column '$pk_col' not found in table '$tbl_name'");
7
	}
8
	$this->tbl_name = $tbl_name;
9
	$this->pk_col = $pk_col;
10
	$this->CI->load->library('table');
11
	
12
}

We have much going on already; but don't worry, as I'll explain everything for you in the next paragraph.

The constructor takes two arguments: the first one being the name of the table in your database that you wish to display as a datagrid to the user; the second param is the name of the column serving as the primary key for that table (more on that later). Inside the constructor's body, we instantiate the CodeIgniter Object, the Database Object and the HTML Table class/library. All of these will be needed throughout a Datagrid object's lifetime and are already built into the CI framework. Notice that we also check if the primary key really exists in the given table, and, in case it does not, we throw an exception reporting the error. Now the $this->tbl_fields member variable will be available for later use, so we don't have to fetch the database again.

"We can use the command, $CI->db->list_fields($tbl_name) to fetch the names of all fields that a table has. However, for better performance, I recommend caching the results."

Method for Customizing Table Headings

1
public function setHeadings(array $headings){
2
	$this->headings = array_merge($this->headings, $headings);
3
}

This permits you to customize the headings of your data grid table - that is, with it, you can overwrite the original column names for certain table fields. It takes an associative array, like this: regdate => "Registration Date". Instead of just the technical "Regdate" as the column heading for that type of data, we have a more human-readable title in its place. The code responsible for applying the headings will be revealed shortly.

Method for Ignoring/Hiding Table Fields

1
public function ignoreFields(array $fields){
2
	foreach($fields as $f){
3
		if($f!=$this->pk_col)
4
			$this->hide_cols[] = $f;
5
	}
6
}

ignoreFields receives an array containing the fields to be ignored when fetching data from the database. This is useful when we have tables with lots of fields, but we only want to hide a couple of them. This method is smart enough to track an attempt to ignore the primary key field and then skip that. This is so because the primary key cannot be ignored for technical reasons (you will see why shortly). Still, if you want to hide the primary key column from appearing in the UI, you can use the hidePkCol method:

1
public function hidePkCol($bool){
2
	$this->hide_pk_col = (bool)$bool;
3
}

This method receives a boolean value to indicate if we want to hide the primary key column so it won't show up in the data grid. Sometimes, it's an ugly idea to display the pkey data, which is usually a numerical code without any meaning to the user.

Next instance method:

1
private function _selectFields(){
2
	foreach($this->tbl_fields as $field){
3
		if(!in_array($field,$this->hide_cols)){
4
			$this->CI->db->select($field);
5
			// hide pk column heading?

6
			if($field==$this->pk_col && $this->hide_pk_col) continue;
7
				$headings[]= isset($this->headings[$field]) ? $this->headings[$field] : ucfirst($field);
8
		}
9
	}
10
	if(!empty($headings)){
11
		// prepend a checkbox for toggling 

12
		array_unshift($headings,"<input type='checkbox' class='check_toggler'>");
13
		$this->CI->table->set_heading($headings);
14
	}
15
	
16
}

Here we have a helper method; that's why it has the "private" modifier and is prefixed with an underline character (code convention). It will be used by the generate() method - explained shortly - in order to have the appropriate table fields selected and also the appropriate headings set to the table (generator) object. Notice the following line:

1
$headings[]= isset($this->headings[$field]) ? $this->headings[$field] : ucfirst($field);

This is where we apply the customized headers or resort to the default ones if none is given. If the pk column is supposed to be hidden from display, then it's heading will be skipped. Also notice the following line:

1
array_unshift($headings,"<input type='checkbox' class='dg_check_toggler'>");

The above command instructs the program to prepend a "Master" checkbox as the first heading of the table. That checkbox is different from other checkboxes in the grid in that it allows a user to check or uncheck all checkboxes in just one go. This toggling functionality will be implemented in a few moments with a simple jQuery code snippet.

Method to Generate/Render the Datagrid

Now comes the thing that does the real work for us:

1
public function generate(){
2
	$this->_selectFields();
3
	$rows = $this->CI->db
4
			->from($this->tbl_name)
5
			->get()
6
			->result_array();
7
	foreach($rows as &$row){
8
		$id = $row[$this->pk_col];
9
		
10
		// prepend a checkbox to enable selection of items/rows

11
		array_unshift($row, "<input class='dg_check_item' type='checkbox' name='dg_item[]' value='$id' />");
12
		
13
		// hide pk column cell?

14
		if($this->hide_pk_col){
15
			unset($row[$this->pk_col]);
16
		}
17
	}
18
	
19
	return $this->CI->table->generate($rows);
20
}

The generate method, as its name suggests, is responsible for generating the data grid itself. You should call this method only after you have configured the object according to your needs. The first thing it does is call the $this->_selectFields() method to perform the actions we explained earlier. Now it has to fetch all rows from the database and then loop through them, adding checkboxes to the beginning of each row:

1
// prepend a checkbox to enable selection of items/rows

2
array_unshift($row, "<input class='dg_check_item' type='checkbox' name='dg_item[]' value='$id' />");

Inside the foreach loop on the generate method, if the $this->hide_pk_col flag is set to true, then we must unset the primary key entry in the $row array so it won't show up as a column when the $this->CI->table object processes all rows and generates the final html output. At this point, it is okay to remove the primary key, if necessary, because we no longer need that information. A

But what does the user do with the selected/checked rows? To answer this, I have prepared a few more methods. The first one enables us to create "action buttons" without having to know any technical details about how the grid system works internally:

Method for Adding Buttons to a Data Grid Form

1
public static function createButton($action_name, $label){
2
	return "<input type='submit' class='$action_name' name='dg_action[$action_name]' value='$label' />";
3
}

Simply pass the name of the action as the first argument and a second argument to indicate the label for the generated button. A class attribute is automatically generated for that button so we can play around with it more easily when we are working with it in our JavaScript. But, how do we know if a certain action button has been pressed by the user? The answer can be found in the next method:

1
public static function getPostAction(){
2
// get name of submitted action (if any)

3
	if(isset($_POST['dg_action'])){
4
		return key($_POST['dg_action']);
5
	}
6
}

Yep! Another static method that helps us when we are dealing with forms. If any data grid has been submitted, this method will return the name of the action (or "operation") associated with that submit event. In addition, another handy tool for processing our datagrid forms is...

1
public static function getPostItems(){
2
	if(!empty($_POST['dg_item'])){
3
		return $_POST['dg_item'];
4
	}
5
	return array();
6
}

... which returns an array containing the selected ids so you can track which rows have been selected on the grid and then perform some action with them. As an example of what can be done with a selection of row ids, I have prepared another method - this one being an instance method, and not a static one, because it makes use of the object's instance resources in order to do its business:

1
public function deletePostSelection(){
2
// remove selected items from the db

3
	if(!empty($_POST['dg_item']))
4
		return $this->CI->db
5
			->from($this->tbl_name)
6
			->where_in($this->pk_col,$_POST['dg_item'])
7
			->delete();
8
}

If at least one checkbox was checked, the deletePostSelection() method will generate and execute an SQL statement like the following (suppose $tbl_name='my_table' and $pk_col='id'):

1
DELETE FROM my_table WHERE id IN (1,5,7,3,etc...)

...which will effectively remove the selected rows from the persistent layer. There could be more operations you could add to a data grid, but that will depend on the specifics of your project. As a tip, you could extend this class to, say, InboxDatagrid, so, beyond the deletePostSelection method, it could include extra operations, such as moveSelectedMessagesTo($place), etc...

Putting everything together

Now, if you have followed this tutorial step by step, you should have ended up with something similar to the following:

1
class Datagrid{
2
	
3
	private $hide_pk_col = true;
4
	private $hide_cols = array();
5
	private $tbl_name = '';
6
	private $pk_col	= '';
7
	private $headings = array();
8
	private $tbl_fields = array();
9
	
10
	function __construct($tbl_name, $pk_col = 'id'){
11
		$this->CI =& get_instance();
12
		$this->CI->load->database();
13
		$this->tbl_fields = $this->CI->db->list_fields($tbl_name);
14
		if(!in_array($pk_col,$this->tbl_fields)){
15
			throw new Exception("Primary key column '$pk_col' not found in table '$tbl_name'");
16
		}
17
		$this->tbl_name = $tbl_name;
18
		$this->pk_col = $pk_col;
19
		$this->CI->load->library('table');
20
		
21
	}
22
	
23
	public function setHeadings(array $headings){
24
		$this->headings = array_merge($this->headings, $headings);
25
	}
26
	
27
	public function hidePkCol($bool){
28
		$this->hide_pk_col = (bool)$bool;
29
	}
30
	
31
	public function ignoreFields(array $fields){
32
		foreach($fields as $f){
33
			if($f!=$this->pk_col)
34
				$this->hide_cols[] = $f;
35
		}
36
	}
37
	
38
	private function _selectFields(){
39
		foreach($this->tbl_fields as $field){
40
			if(!in_array($field,$this->hide_cols)){
41
				$this->CI->db->select($field);
42
				// hide pk column heading?

43
				if($field==$this->pk_col && $this->hide_pk_col) continue;
44
				$headings[]= isset($this->headings[$field]) ? $this->headings[$field] : ucfirst($field);
45
			}
46
		}
47
		if(!empty($headings)){
48
			// prepend a checkbox for toggling 

49
			array_unshift($headings,"<input type='checkbox' class='dg_check_toggler'>");
50
			$this->CI->table->set_heading($headings);
51
		}
52
		
53
	}
54
	
55
	public function generate(){
56
		$this->_selectFields();
57
		$rows = $this->CI->db
58
				->from($this->tbl_name)
59
				->get()
60
				->result_array();
61
		foreach($rows as &$row){
62
			$id = $row[$this->pk_col];
63
			
64
			// prepend a checkbox to enable selection of items

65
			array_unshift($row, "<input class='dg_check_item' type='checkbox' name='dg_item[]' value='$id' />");
66
			
67
			// hide pk column?

68
			if($this->hide_pk_col){
69
				unset($row[$this->pk_col]);
70
			}
71
		}
72
		
73
		return $this->CI->table->generate($rows);
74
	}
75
	
76
	public static function createButton($action_name, $label){
77
		return "<input type='submit' class='$action_name' name='dg_action[$action_name]' value='$label' />";
78
	}
79
	
80
	public static function getPostAction(){
81
	// get name of submitted action (if any)

82
		if(isset($_POST['dg_action'])){
83
			return key($_POST['dg_action']);
84
		}
85
	}
86
	
87
	public static function getPostItems(){
88
		if(!empty($_POST['dg_item'])){
89
			return $_POST['dg_item'];
90
		}
91
		return array();
92
	}
93
	
94
	public function deletePostSelection(){
95
	// remove selected items from the db

96
		if(!empty($_POST['dg_item']))
97
			return $this->CI->db
98
				->from($this->tbl_name)
99
				->where_in($this->pk_col,$_POST['dg_item'])
100
				->delete();
101
	}
102
103
}

Notice: Don't forget to save this file as datagrid_helper.php, and place it in "application/helper/"


Step 2: Testing the Datagrid Helper Class with a CodeIgniter Controller

We'll now create a simple test controller and load the Datagrid class as a helper in its constructor. But before that, we should define a dummy database table and populate it with some sample data.

Execute the following SQL to create the database and the user table:

1
CREATE DATABASE `dg_test`;
2
CREATE TABLE `users` (
3
  `id` int(11) NOT NULL AUTO_INCREMENT,
4
  `username` varchar(80) NOT NULL,
5
  `password` varchar(32) NOT NULL,
6
  `email` varchar(255) NOT NULL,
7
  UNIQUE KEY `id` (`id`)
8
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

Next, let's add some users to it:

1
INSERT INTO `users` (`id`, `username`, `password`, `email`) VALUES
2
(1, 'david', '12345', 'david@domain.com'),
3
(2, 'maria', '464y3y', 'maria@domain.com'),
4
(3, 'alejandro', 'a42352fawet', 'alejandro@domain.com'),
5
(4, 'emma', 'f22a3455b2', 'emma@domain.com');

Now, save the following code as "test.php," and add it to the "application/controllers" folder:

1
<?php
2
class Test extends CI_Controller{
3
4
	function __construct(){
5
		parent::__construct();
6
		$this->load->helper(array('datagrid','url'));
7
		$this->Datagrid = new Datagrid('users','id');
8
	}
9
	
10
	function index(){
11
		$this->load->helper('form');
12
		$this->load->library('session');
13
14
		$this->Datagrid->hidePkCol(true);
15
		$this->Datagrid->setHeadings(array('email'=>'E-mail'));
16
		$this->Datagrid->ignoreFields(array('password'));
17
		
18
		if($error = $this->session->flashdata('form_error')){
19
			echo "<font color=red>$error</font>";
20
		}
21
		echo form_open('test/proc');
22
		echo $this->Datagrid->generate();
23
		echo Datagrid::createButton('delete','Delete');
24
		echo form_close();
25
	}
26
	
27
	function proc($request_type = ''){
28
		$this->load->helper('url');
29
		if($action = Datagrid::getPostAction()){
30
			$error = "";
31
			switch($action){
32
				case 'delete' :
33
					if(!$this->Datagrid->deletePostSelection()){
34
						$error = 'Items could not be deleted';
35
					}
36
				break;
37
			}
38
			if($request_type!='ajax'){
39
				$this->load->library('session');
40
				$this->session->set_flashdata('form_error',$error);
41
				redirect('test/index');
42
			} else {
43
				echo json_encode(array('error' => $error));
44
			}
45
		} else {
46
			die("Bad Request");
47
		}
48
	}
49
50
}
51
?>

An instance of this class is created and passed as a reference to the $this->Datagrid member. Notice that we will be fetching data from a table called "users" whose primary key is the "id" column; then, on the index method we take the following steps: configure the Datagrid object, render it inside a form with a delete button added to it and see if everything works as expected:

Question: What happens when the form is sent?

Answer: The "Test::proc()" method takes care of processing the form and choosing the right operation to apply against the ids that were selected by the form's sender. It also takes care of AJAX requests, so it will echo a JSON object back to the client. This AJAX-aware feature will come in handy when jQuery comes into action, which is right now!

"It's always a smart idea to create web applications which compensates for when JavaScript/AJAX is unavailable. This way, some users will have a richer and faster experience, while those without JavaScript enabled will still be able to use the application normally."


Step 3: Implementing Ajax (jQuery to the Rescue!)

When the user clicks the button (or any other action button), we would like, perhaps, to prevent the page from reloading and having to generate everything again; this could make the user of our application fall asleep! Circumventing this problem will not be a difficult task if we stick to the jQuery library. Since this is not a "beginners" tutorial, I will not go through all the details related to how to get the library, how to include it on the page, etc. You're expected to know these steps on your own.

Create a folder, named "js", add the jQuery library within, and create a view file, named users.php. Open this new file, and add:

1
<html>
2
<head>
3
	<title>Users Management</title>
4
	<script src="<?php echo base_url(); ?>js/jquery-1.6.3.min.js"></script>
5
	<script src="<?php echo base_url(); ?>js/datagrid.js"></script>
6
</head>
7
<body>
8
<?php

9
		$this->Datagrid->hidePkCol(true);

10
		if($error = $this->session->flashdata('form_error')){

11
			echo "<font color=red>$error</font>";

12
		}

13
		echo form_open('test/proc',array('class'=>'dg_form'));

14
		echo $this->Datagrid->generate();

15
		echo Datagrid::createButton('delete','Delete');

16
		echo form_close();

17
?>
18
</body>
19
</html>

Did you realize that we have moved the code away from Test::index and into the new view script? This means we must change the Test::index() method accordingly:

1
function index(){
2
	$this->load->helper('form');
3
	$this->load->library('session');
4
	$this->load->view('users');
5
}

That's better. If you want to add some styling to the grid, you could use the following CSS (or make a better layout on your own):

1
	.dg_form table{
2
		border:1px solid silver;
3
	}
4
	
5
	.dg_form th{
6
		background-color:gray;
7
		font-family:"Courier New", Courier, mono;
8
		font-size:12px;
9
	}
10
	
11
	.dg_form td{
12
		background-color:gainsboro;
13
		font-size:12px;
14
	}
15
	
16
	.dg_form input[type=submit]{
17
		margin-top:2px;
18
	}

Now, please, create a "datagrid.js" file, put it on the "js" directory, and start with this code:

1
$(function(){
2
	// cool stuff here...
3
})

Inside this closure, we will write code that will be tasked with controlling certain submit events once the page has completely loaded. The first thing we need to do is track when a user clicks a submit button on the data grid form, and then send that data to be processed on the server.

1
 	$('.dg_form :submit').click(function(e){
2
		e.preventDefault();
3
		var $form = $(this).parents('form');
4
		var action_name = $(this).attr('class').replace("dg_action_","");
5
		var action_control = $('<input type="hidden" name="dg_action['+action_name+']" value=1 />');
6
		
7
		$form.append(action_control);
8
		
9
		var post_data = $form.serialize();
10
		action_control.remove();
11
		
12
		var script = $form.attr('action')+'/ajax';
13
		$.post(script, post_data, function(resp){
14
			if(resp.error){
15
				alert(resp.error);
16
			} else {
17
				switch(action_name){
18
					case 'delete' :
19
						// remove deleted rows from the grid
20
						$form.find('.dg_check_item:checked').parents('tr').remove();
21
					break;
22
					case 'anotherAction' :
23
						// do something else...
24
					break;
25
				}
26
			}
27
		}, 'json')
28
	})

Alternatively, we could have started with something like: $('.dg_form').submit(function(e){...}). However, since I want to track which button has been pressed and extract the name of the chosen action based on it, I prefer binding an event handler to the submit button itself and then go my way up the hierarchy of nodes to find the form that the pressed button belongs to:

1
// finds the form

2
var $form = $(this).parents('form');
3
// extracts the name of the action

4
var action_name = $(this).attr('class').replace("dg_action_","");

Next, we add a hidden input element inside the form element to indicate which action is being sent:

1
// create the hidden input

2
var action_control = $('<input type="hidden" name="dg_action['+action_name+']" value=1 />');
3
// add to the form

4
$form.append(action_control);

This is necessary because function doesn't consider the submit button to be a valid form entry. So we must have that hack in place when serializing the form data.

1
action_control.remove();

"Don't forget: the function ignores the submit button, dismissing it as just another piece of markup junk!"

Sending Form Data to the Server

Next, we proceed to get the action attribute from the form element and append the string "/ajax" to that url, so the method will know that this is, in fact, an AJAX request. Following that, we use the jQuery.post function to send the data to be processed by the appropriate controller, server-side, and then intercept the response event with a registered callback/closure:

1
...
2
	var script = $form.attr('action')+'/ajax';
3
	$.post(script, post_data, function(resp){
4
		if(resp.error){
5
			alert(resp.error);
6
		} else {
7
			switch(action_name){
8
				case 'delete' :
9
					// remove deleted rows from the grid
10
					$form.find('.dg_check_item:checked').parents('tr').remove();
11
				break;
12
				case 'anotherAction' :
13
					// do something else...
14
				break;
15
			}
16
		}
17
	},'json')

Notice that we are asking the response to be encoded as "json" since we are passing that string as the fourth argument of the $.post function. The contents of the callback dealing with the server response should be rather simple to grasp; it determines if there is an error, and, if so, alerts it. Otherwise, it will indicate that the action was successfully processed (in this case, if it is a "" action, we remove the rows related to the ids that were selected by the user).


Step 4: Check All or Nothing!

The only thing that is missing now is the toggle functionality that I promised earlier. We must register a callback function for when the "Master" checkbox - which has a class attribute set to "dg_check_toggler" - is clicked. Add the following code snippet after the previous one:

1
	$('.dg_check_toggler').click(function(){
2
		var checkboxes = $(this).parents('table').find('.dg_check_item');
3
		if($(this).is(':checked')){
4
			checkboxes.attr('checked','true');
5
		} else {
6
			checkboxes.removeAttr('checked');
7
		}
8
	})

When the "toggler" checkbox is clicked, if it goes to a "checked" state, then all rows from the pertaining data grid will be checked simultaneously; otherwise everything will be unchecked.


Final Thoughts

We haven't reached the tip of the iceberg when it comes to data grids for more complex content management systems. Other features which might prove to be useful are:

  • Sorting the data grid by column names
  • Pagination links for browsing the data grid
  • Edit/Modify links for updating a single row's data
  • Search mechanism to filter results

Thanks for reading. If you'd like a follow-up tutorial, let me know in the comments!

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.