Ajax Todo List system with Codeigniter Part 1


I am going to write how to create an ajax message/todo system with Codeigniter. All the following features will be done with Ajax. And the message will be stored in a database.

Demo

Download Files

  1. There will be Todo list and Completed list loaded with jquery.
  2. Adding a todo list without page reload.
  3. Clicking a link in a todo list will change to a completed list.
  4. The list clicked will slide up and removed. The completed list will fade out and fade in with a new list added from todo list
  5. There will be the same button in a completed list. This will change the status from complete to todo. It will slide up and removed. Todo list will fade out and in with a list from the completed list.
  6. Delete button will be added in completed lists. When you click this, it will be removed from the database and it will slide up and removed.
 

There will be three parts to develop this system.

  1. Setting up Codeigniter and BackendPro
  2. Create message system with codeigniter. It should work without js.
  3. Add jquery ajax.

It will be too long to cover all of these. I will cover the first two in this entry and the last one will be the next time.

You can find a quite few login systems in Codeigniter wiki. So far I like BackendPro and Pyrocms. I will use BackendPro for the login system.

Setting up

Download Codeigniter ,BackendPro and install them. You can find here how to install the BackendPro.

However this is what I did on my localhost. I am using XAMPP.

  1. Create a folder called ci_bep like this C:\xampp\htdocs\ci_bep.Unzip the Codeigniter in this folder.
  2. Unzip the BackendPro and move all the folders in C:\xampp\htdocs\ci_bep as well.
  3. Create a database called ci_bep or any name as you like.
  4. Go to http://127.0.0.1/ci_bep/install/ or http://localhost/ci_bep/install/ and proceed the installation process.
  5. Enter your database details, User account and reCAPTCHA information if you wish. You can get your public and private key here. I am not using this in this tutorial so you can skip it if you like.
  6. Click INSTALL BACKENDPRO at the bottom. That’s it.
  7. Use your email and password which you entered during the installation to login the BackendPro.

Adding Message Database

Add the following database.

CREATE TABLE IF NOT EXISTS `shoutbox` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `user` varchar(25) NOT NULL DEFAULT 'anonimous',
  `user_id` int(25) NOT NULL,
  `message` varchar(255) NOT NULL DEFAULT '',
  `status` enum('to do','completed') NOT NULL DEFAULT 'to do',
  `privacy` enum('public','private') NOT NULL DEFAULT 'public',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=125 ;

Creating Messages Module folder

Now you go to C:\xampp\htdocs\ci_bep\modules and create the following folders and files. If you are using PhpMyadmin, go to ci_bep and click SQL on the main tab and paste the following and click GO.

modules\messages\
modules\messages\controllers\
modules\messages\controllers\admin.php
modules\messages\models\
modules\messages\models\mmessages.php
modules\messages\views
modules\messages\views\admin
modules\messages\views\admin\admin_messages_home.php
modules\messages\
modules\messages\

Adding Navigation

We need to add a navigation in the main menu on the left. Open C:\xampp\htdocs\ci_bep\system\application\views\admin. And change to the following code.

<!--
When creating a new menu item on the top-most level
Please ensure that you assign the LI a unique ID

Examples can be seen below for menu_bep_system
-->

<ul id="menu">
    <li id="menu_bep_home"><?php print anchor('admin',$this->lang->line('backendpro_dashboard'),array('class'=>'icon_house'))?></li>
    <?php if(check('System',NULL,FALSE)):?>
    <li id="menu_bep_system"><span class="icon_computer"><?php print $this->lang->line('backendpro_system')?></span>
        <ul>
            <?php if(check('Members',NULL,FALSE)):?><li><?php print anchor('auth/admin/members',$this->lang->line('backendpro_members'),array('class'=>'icon_group'))?></li><?php endif;?>
            <?php if(check('Access Control',NULL,FALSE)):?><li><?php print anchor('auth/admin/access_control',$this->lang->line('backendpro_access_control'),array('class'=>'icon_shield'))?></li><?php endif;?>
            <?php if(check('Settings',NULL,FALSE)):?><li><?php print anchor('admin/settings',$this->lang->line('backendpro_settings'),array('class'=>'icon_cog'))?></li><?php endif;?>
        </ul>
    </li>
    <?php endif;?>
    <li id="menu_bep_general"><span class="icon_general"><?php print $this->lang->line('backendpro_general')?></span>
        <ul>
                 <li><?php print anchor('messages/admin',$this->lang->line('backendpro_messages'),array('class'=>'icon_comment'))?></li>

        </ul>
    </li>
</ul>

Now we need to add languages and icons to show them nicely.

Open C:\xampp\htdocs\ci_bep\system\application\language\english\backendpro_lang.php and add the followings at the end.

/* All Main Controller Names and menu items */

$lang['backendpro_messages'] = 'Messages';

Download an icon set from here and rename one of icon as general.png and move it and comment.png to C:\xampp\htdocs\ci_bep\assets\icons.

Go to the backend and see your new menu on the left.

Creating permission

If you click the link, a warning message comes out and shows the following.

Warning

* You do not have permission to view the page you requested.

We need to work on access control to create a resource.

Find system above your messages. Go to system/access control and click Resources. Click ‘Create Resource’ and add a new name called ‘General’ and select ‘Site’ for parent. Then we create one more called ‘Messages’ and parent is ‘General’. That’s it. If you go to system>Access control>Permissions and click ‘Advanced View Mode’. Select Administrator under Group, you will see what you have created.

Adding security help

Add the following helper in C:\xampp\htdocs\ci_bep\system\application\helpers

<?php
function id_clean($id,$size=11){
	return intval(substr($id,0,$size));
}

function db_clean($string,$size=255){
	return xss_clean(substr($string,0,$size));
}
?>

And open C:\xampp\htdocs\ci_bep\system\application\config\autoload.php and add the security help as follows.

/*
| ----------------------------
|  Auto-load Helper Files
| ----------------------------
| Prototype:
|
|	$autoload['helper'] = array('url', 'file');
*/

$autoload['helper'] = array('security');

We will use this later in model. This helper clean user inputs.

Controller

Now fun parts start. Open C:\xampp\htdocs\ci_bep\modules\messages\controllers\admin.php and add the following codes.

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

class Admin extends Admin_Controller {
  function Admin(){
   parent::Admin_Controller();
   // Check for access permission
	check('Messages');
	// Load model MMessages
	$this->load->model('MMessages');

	// Set breadcrumb
	$this->bep_site->set_crumb($this->lang->line('backendpro_messages'),'messages/admin');	

    }

  function index(){
  	$data['title'] = "Manage Messages";

	$data['user_id'] =$this->session->userdata('id');
	$data['username'] =$this->session->userdata('username');

	$data['todos'] = $this->MMessages->getToDoMessages();
	$data['completed'] = $this->MMessages->getCompletedMessages();

	$data['header'] = $this->lang->line('backendpro_access_control');
	$data['page'] = $this->config->item('backendpro_template_admin') . "admin_messages_home";
	$data['module'] = 'messages';
	$this->load->view($this->_container,$data);

  }

	function getCompletedBox(){

	  		$messages = $this->MMessages->getCompletedMessages();
			flashMsg('success','Status changed');
			redirect ('messages/admin/');

		}

		function insertShoutBox(){

			$this->MMessages->updateMessage();
			flashMsg('success','New task added');
			redirect ('messages/admin/');
		}

	function changestatus($id){
		if($id){
			$this->MMessages->changeMessageStatus($id);
			$this->getCompletedBox();
			flashMsg('success','Status changed');
			redirect ('messages/admin/','refresh');
		}
			flashMsg('warning','Status not changed');
			redirect('messages/admin/','refresh');
	  }

	 function delete($id){
		if($id){
			$this->MMessages->delete($id);
			flashMsg('success','Task deleted');
			redirect('messages/admin/','refresh');
			}
			flashMsg('warning','Task not deleted');
			redirect('messages/admin/','refresh');
	  }

}
  • Line 7 check(‘Messages’); will check if you are allowed to see the page.
  • Line 12 set the breadcrumb
  • Line 17 to 28 set up for index page.
  • Line 19 and 20 get your user_id and username from CI session
  • Line 27 tells which module you are using and used for view page.
  • _container is used to use the normal BackendPro general view.

Model

Open C:\xampp\htdocs\ci_bep\modules\messages\models\mmessages.php and paste the followings.

I am using db_clean and id_clean functions which we added as a helper before.

<?php

class MMessages extends Model{
 function  __construct(){
    parent::Model();
 }

 function updateMessage(){

      $data = array(
		'message' => db_clean($_POST['message']),
		'user_id' => id_clean($_POST['user_id']),
      	        'user' => db_clean($_POST['user'])
	);
      $this->db->insert('shoutbox', $data);
 }

 function getToDoMessages(){
 	// $this->db->limit(10);
     $this->db->order_by("date", "desc");
     $this->db->where('status','to do');
     $Q = $this->db->get('shoutbox');
     if ($Q->num_rows() > 0){
             foreach ($Q->result_array() as $row){
                 $data[] = $row;
             }
         }else{
		 $data = "no to do messages";
		 }
    $Q->free_result();
    return $data; 

 }

 function getCompletedMessages(){
 	 $this->db->order_by("date", "desc");
         $this-&gt;db->where('status','completed');
         $Q = $this->db->get('shoutbox');
     if ($Q->num_rows() > 0){
             foreach ($Q->result_array() as $row){
                 $data[] = $row;
                // $data[$row['id']] = $row;
             }
         }else{
         $data ="No completed tasks.";
         }
    $Q->free_result();
    return $data; 

 }

 function delete($id){
 $id = db_clean($id);
 $this->db->delete('shoutbox', array('id' => $id));
 }

 function changeMessageStatus($id){

	$messageinfo = array();
	$messageinfo = $this->getMessage($id);
	$status = $messageinfo['status'];
	if($status =='to do'){

		$data = array('status' => 'completed');
		$this->db->where('id', id_clean($id));
		$this->db->update('shoutbox', $data);	

	}else{

		$data = array('status' => 'to do');
		$this->db->where('id', id_clean($id));
		$this->db->update('shoutbox', $data);
		}

  }

}

View

Open C:\xampp\htdocs\ci_bep\modules\messages\views\admin_messages_home.php and paste the following codes.

<?php print displayStatus();?>
<div id="homeright"  class="adminhome">
	<form method="post" id="form" action="admin/insertShoutBox" >

		<input type="hidden" name="user_id" id="user_id" value="<?php echo $user_id;?>" />
		<input type="hidden" name="user" id="nick" value="<?php echo $username;?>" />

		<p class="messagelabel"><label class="messagelabel">Message</label>
		<textarea  id="message" name="message" rows="2" cols="40"></textarea>

		<input id="send" type="submit" value="SUBMIT" /></p>

	</form>

	<div id="loading"><img src="../../assets/images/general/ajax-loader2.gif" alt="Loading now. Smile" /></div>
	<div class="clearboth"></div>
	<div id="container">

		<span class="clear"></span>
		<div class="content">
			<h1>Latest Messages or Task To Do</h1>

			<ul id="message_ul" >

			</ul>
			<ul class="hideme">
				<?php
				if(is_array($todos)){
				foreach ($todos as $key => $todo){
				 echo "\n<li class=\"".$todo['id']."\">\n<div class=\"listbox\"><span class=\"user\"><strong>".$todo['user']."</strong></span>\n\n<span class=\"date\" >" .$todo['date']."</span>\n";
				 echo anchor ('messages/admin/changestatus/'.$todo['id'],$todo['status'],array('class'=>'todo'));
				 echo "<span class=\"msg\">".$todo['message'].
				"</span></div></li>";
				}
				}else{
					echo $todos;
				}
				?>
			</ul>

		</div>
	</div>

	<div id="completed">
	<h1>Completed Lists</h1>
	<ul id="completed_ul">

	</ul>

	<ul class="hideme">
		<?php
		if(is_array($completed)){
			foreach ($completed as $key => $list){
			echo "\n<li class=\"".$list['id']."\">\n<span class=\"user\"><strong>".$list['user']."</strong></span>\n<span class=\"date\" >" .$list['date']."</span>\n";
			echo anchor ('messages/admin/changestatus/'.$list['id'],$list['status'],array('class'=>'completedmsg'));
			echo	 "\n<a href=\"admin/delete/"
				 .$list['id']."\" id=\"".$list['id']."\" class=\"delete\">x</a><span class=\"msg\">".$list['message'].
				"</span>\n</li>";
				}
		}else{
					echo $completed;
				}
		?>
	</ul>

		</div>
</div>

It should work by now. But we need to add a bit of style.

CSS

Create admin.css as C:\xampp\htdocs\ci_bep\assets\css\admin.css and paste the followings.

/* admin css */

 .adminhome{
   width: 48%;
   float: left;
 }
 #homeleft{

 }
#homeright{
   width: 95%;

}

#homeright li {
  list-style-type:none;
}

 .message{
 	border:1px solid #c98c21;
 	background-color:#efdda8;
 	color:#c98c21;
 	padding:5px;
 	width:250px;
 	font-size:12px;
 	margin:5px 0px 5px 0px;
 }

/******* CONTENT *******/
.content p{
	margin: 0pt auto;
	width:90%;
	text-align: left;
	padding: 10px;
	float:left;
	font-size: 13px;
}
.content li, #completed li{
	border: 1px solid #d0ccc9;
	background: #efefef;
	margin:5px;
	padding: 5px;

}
#completed ul, #message_ul {

	margin: 0;
	padding:0;
}
.content .delete {
	font-size: 14px;
	padding: 5px;
	margin: 0 0 5px 0;

}
.content h1, #completed h1{
	line-height: 1em;
	vertical-align: middle;
	height: 18px;
	padding: 10px 10px 10px 52px;
	font-size: 16px;
	background: transparent url(images/bubble.jpg) no-repeat scroll left top;
}
.content li a, #completed li a{
	width: 30px;

	padding: 0 10px;
}
.listbox{

}
.date{
	font-weight: normal;
	font-size: 10px;
	color: #aeaeae;
	padding: 0 3px;
}
.user{

}
.msg{
	padding: 5px 0;
	display:block;
}

#message {
	margin:0;
	padding: 0;
}

.messagelabel {
	width: 100%;
	padding: 5px 0;
	margin : 0;

}
.text {
	float:left;
}
.msguser{
	padding: 0 26px 0 0;
}
#send {
	margin: 0 0 0 15px;
}

/******* LOADING *******/
#loading{
	text-align: center;
}

#completed {
	float:left;
	width:46%;
}
#container {
	float: left;
	width:46%;
}

#form {
	width: 400px;
	float: left;
}
#loading{
	width: 70px;
	float:left;
	padding-top: 35px;
}
#showall{
	height: 50px;
	width: 170px;
	float:left;
	padding: 35px 0 0 0;
}
.clearboth{
	clear:both;
}

How to add CSS

Now we need to add this css. But BackendPro has a special way to add assets. Open C:\xampp\htdocs\ci_bep\modules\site\config\bep_assets.php and add this line after BackendPro CSS around line 77.

// Admin CSS
$config['asset'][] = array('file'=>'admin.css');

And add admin in the ‘asset_group ADMIN like this.

$config['asset_group']['ADMIN'] = 'bep_admin_layout|bep_admin_style|FlashStatus|forms|buttons|bep_navigation|treeview|bep_icons|bep_select_all|admin';

This is how BackendPro controls all the assets including javascripts.

Test drive

Now you add tasks. Click todo to see that will change to the completed list and vise versa. Clicl a cross x to delete your list.

Next

In the next entry, I will make this one to Ajax.

Download

7 comments to Ajax Todo List system with Codeigniter Part 1

  • Mario

    Hi there,
    If i install backendpro i get the result “BackendPro Install was Successful”.

    But when I go to the root of my site I get a lot of errors. What went wrong?

    Errors:

    Severity: 8192
    Message: Assigning the return value of new by reference is deprecated
    Filename: libraries/Loader.php
    Line Number: 414

    Severity: Warning
    Message: Cannot modify header information – headers already sent by (output started at C:\Program Files\xampp\htdocs\test\system\application\libraries\Loader.php:414)
    Filename: libraries/Session.php
    Line Number: 662

  • shinokada

    I have two suggestions. 1. Ask BackendPro forum. The forum is very active. You get a reply soon.

    2. Why don’t you download my files and run SQL to install the database. Go to the Part 2 of this article. It has all the files.

  • [...] Ajax Todo List system with Codeigniter Part 1 Via / @farotto [...]

  • [...] Ajax Todo List system with Codeigniter [...]

  • Tibor

    Hi
    Thanks for your nice tutorial
    is the Ajax version out yet ?
    Regadrs
    Tbor

  • shinokada

    Yes, you can see here. You can download the file from Downloads page.

  • name

    @mario
    i have same problem like you..
    may be you can solve your problem with this step:
    1. got to “ci_bep\system\application\libraries\loader.php”
    2. on line 414 ,remove “&”..
    before : ” $CI->dbutil =& new $class();”
    after : ” $CI->dbutil = new $class();”

    hope your problem can solve..

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>