Interactive Ajax Data Management with Codeigniter
March 20th, 2011 by dr.emi
![]()
Hi there! this is super fast tutorial, when I was take a rest at the room. Oh god, where is my cofee and PUNK music. Aha!
This tutorial will show to you, how to create Interactive and very fast data management on one page together, without refreshing any page. One thing make this better “You are in codeigniter class of dr.emi” So, enjoy this tutorial.
First, we need some ammunition:
1. Codeigniter framework
2. jQuery framework
3. Netbeans IDE
4. Colorbox jQuery plugin
Part #1 Create database
CREATE TABLE `blog` ( `id` int(11) NOT NULL auto_increment, `title` varchar(255) NOT NULL, `content` text NOT NULL, `date` datetime NOT NULL, PRIMARY KEY (`id`) ) AUTO_INCREMENT=1;
Part #2 Codeigniter configuration
Open your base configuration and database configuration on folder ./application/config/
>>> autoload.php
$autoload['libraries'] = array('database');
$autoload['helper'] = array('html', 'url', 'form', 'template');
$autoload['model'] = array('Blog_model');
>>> database.php
$active_group = 'default'; $active_record = TRUE; $db['default']['hostname'] = 'localhost'; $db['default']['username'] = 'root'; $db['default']['password'] = 'dremi_still_here'; $db['default']['database'] = 'interactive_ajax_data_management';
Part #3 Create Blog Controller
Create new class file on ./application/controllers/ and save as blog.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Description of blog controller
*
* @author dr.emi
*/
class Blog extends CI_Controller {
function Blog() {
parent::__construct();
}
function index() {
$data = array(
'query' => $this->Blog_model->get_last_ten_entries()
);
$this->load->view('blog/index', $data);
}
function entries() {
$data = array(
'query' => $this->Blog_model->get_last_ten_entries()
);
$this->load->view('blog/entries', $data);
}
function form() {
$data = $this->Blog_model->current_entry();
$this->load->view('blog/form', $data);
}
function save() {
$this->Blog_model->save_entry();
}
function confirm() {
$this->load->view('blog/confirm');
}
function delete() {
$this->Blog_model->delete_entry();
}
}
Part #4 Create Blog Model
Create new class file on <strong>./application/models/</strong> and save as <strong>blog_model.php</strong>
1
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Description of blog model
*
* @author dr.emi
*/
class Blog_model extends CI_Model {
function __construct() {
// Call the Model constructor
parent::__construct();
}
function get_last_ten_entries() {
$this->db->order_by("id", "desc");
$query = $this->db->get('blog', 10);
return $query;
}
function save_entry() {
$tabledata = get_table_fld('blog');
$data = post2data($tabledata);
$id = store_data('blog',$data,'id');
}
function delete_entry() {
$this->db->delete('blog', array('id' => $this->uri->segment(3)));
}
function current_entry() {
// Get Table Fields
$fields = get_table_fld('blog');
$data = make_array_key($fields);
$this->db->where('id', $this->uri->segment(3));
$sql = $this->db->get('blog');
$row = (array) $sql->row();
$data = array_merge($data, $row);
return $data;
}
}
Everything is fine, if you read codeigniter user guide. I just wanna tell you about the main concept on this tutorial. So, what the next?
Part #5 Create Template Helper
Create new class file on ./application/helpers/ and save as template_helper.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* @author dr.emi
* @copyright 2010
*/
function get_table_fld($table) {
$_this = & get_Instance();
$sql = "show columns from $table ";
$res = $_this->db->query($sql);
$rows = $res->result();
foreach($rows as $r){
$fld[] = $r->Field;
}
$fld = implode(';',$fld);
return ($fld);
}
function make_array_key($str) {
$ar = array();
$key = explode(';',$str);
foreach($key as $k){
$t = array($k=>'');
$ar = array_merge($ar,$t);
}
return $ar;
}
function post2data($str) {
$_this = & get_Instance();
$key = explode(';',$str);
foreach($key as $k){
if($_this->input->post($k)=='' ) continue;
$data[$k] = ltrim(rtrim($_this->input->post($k)));
}
return $data;
}
function store_data($table,& $data,$id) {
$_this = & get_Instance();
$result=0;
if($_this->input->post($id)==''){
if($_this->db->insert($table,$data)) {
//$data[$id] = mysql_insert_id();
$result = mysql_insert_id();
}
} else {
$_this->db->where($id,$_this->input->post($id));
if($_this->db->update($table,$data)) //update($table = '', $set = NULL, $where = NULL, $limit = NULL)
$result = $_this->input->post($id);
}
return $result;
}
Part #6 Create View of blog cotroller
==========MAIN CONCEPT==========
In this case, we will create it on new folder ./application/view/blog/
So, create all view into blog folder.
Then, we will load jQuery, colorbox, and a custom JS. Happy call the script!
<?php echo link_tag('public/css/style.css'); ?>
<?php echo link_tag('public/css/colorbox.css'); ?>
<script type="text/javascript" src="<?php echo base_url(); ?>public/js/jquery.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>public/js/jquery.colorbox.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>public/js/custom.js"></script>
Now, here is the main concept about the auto load dynamic content. We will open form, confirmation dialog, and action on one page without refresh current page. The strategy is: create two different ID on document as target. One as first init content, and the other as new content. When action is complete, we will reload the current content from entries.php file. We need, ajax jQuery here, and will show to you.
<div id="newEntries"><!--NEW CONTENT HERE, AS entries.php target--></div> <div id="firstEntries"><!--FIRST CONTENT HERE--></div>
Remember, we have created function on blog controller class. So, use it! Here are the main function that will used on processing data.
function entries() >>> as result of table content
function form() >>> as colorbox pop up content while ajax request form.php view
function save() >>> as action while submit form, there are two condition: save new record and update new record
function confirm() >>> as colorbox pop up content while ajax request confirm.php view
function delete() >>> as action while delete record
Part #6.A Index.php view
<?php echo link_tag('public/css/style.css'); ?>
<?php echo link_tag('public/css/colorbox.css'); ?>
<script type="text/javascript" src="<?php echo base_url(); ?>public/js/jquery.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>public/js/jquery.colorbox.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>public/js/custom.js"></script>
<h1>Last 10 Entries</h1>
<a href="<?php echo site_url().'/blog/form'; ?>" return="<?php echo site_url().'/blog/entries'; ?>" id="popUpTrigger">Insert new record</a>
<div id="newEntries"></div>
<div id="firstEntries">
<table width="80%" cellpadding="1" cellspacing="1" bgcolor="#cecece" style="margin-top: 30px;">
<thead style="font-weight: bold;">
<tr bgcolor="#ffffff">
<td>#</td>
<td>Title</td>
<td>Date</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php
if ($query->num_rows() > 0)
{
$i = 0;
foreach($query->result() as $row) { $i++;
?>
<tr bgcolor="#ffffff">
<td><?php echo $i; ?></td>
<td><a id="popUpEditFormTrigger" return="<?php echo site_url().'/blog/entries'; ?>" href="<?php echo site_url().'/blog/form/'.$row->id; ?>"><?php echo $row->title; ?></a></td>
<td><?php echo $row->date; ?></td>
<td><a id="popUpDeleteTrigger" return="<?php echo site_url().'/blog/entries'; ?>" href="<?php echo site_url().'/blog/confirm/'.$row->id; ?>">Delete</a></td>
</tr>
<?php
}
} else {
?>
<tr bgcolor="#ffffff">
<td colspan="4" align="center">No data!</td>
</tr>
<?php
}
?>
</tbody>
</table>
Part #6.B Form.php view
<script type="text/javascript" src="<?php echo base_url(); ?>public/js/form.js"></script>
<?php
echo form_fieldset('Blog form');
$hidden = array('id' => $id);
echo form_open('blog/save', 'method="post" id="updateForm"', $hidden);
echo form_label('Title', 'title');
echo '<br />';
echo form_input('title', $title, 'id="title"');
echo '<hr style="color: #f1f1f1;background-color: #c0c0c0;height: 2px;">';
echo form_label('Title', 'title');
echo '<br />';
echo form_textarea('content', $content, 'id="content"');
echo '<hr style="color: #f1f1f1;background-color: #c0c0c0;height: 2px;">';
echo form_button('Save', 'submit', 'id="submitForm"');
echo form_close();
echo form_fieldset_close();
?>
Part #6.C Entries.php view
<table width="80%" cellpadding="1" cellspacing="1" bgcolor="#cecece" style="margin-top: 30px;">
<thead style="font-weight: bold;">
<tr bgcolor="#ffffff">
<td>#</td>
<td>Title</td>
<td>Date</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php
if ($query->num_rows() > 0)
{
$i = 0;
foreach($query->result() as $row) { $i++;
?>
<tr bgcolor="#ffffff">
<td><?php echo $i; ?></td>
<td><a id="popUpEditFormTrigger" return="<?php echo site_url().'/blog/entries'; ?>" href="<?php echo site_url().'/blog/form/'.$row->id; ?>"><?php echo $row->title; ?></a></td>
<td><?php echo $row->date; ?></td>
<td><a id="popUpDeleteTrigger" return="<?php echo site_url().'/blog/entries'; ?>" href="<?php echo site_url().'/blog/confirm/'.$row->id; ?>">Delete</a></td>
</tr>
<?php
}
} else {
?>
<tr bgcolor="#ffffff">
<td colspan="4 align="center">No data!</td>
</tr>
<?php
}
?>
</tbody>
</table>
Part #6.D Confirm.php view
<script type="text/javascript" src="<?php echo base_url(); ?>public/js/form.js"></script> <h1>Are you sure?</h1> <p>Are you sure you want to delete this record #<?php echo $this->uri->segment(3); ?>?</p> <p><strong>Note:</strong> This cannot be undone!</p> <input type="button" id="confirmDeleteButton" action="<?php echo site_url().'/blog/delete/'.$this->uri->segment(3); ?>" value="Yes"> <input type="button" id="cancelDeleteButton" value="No">
While delete link on entries row clicked, will call colorbox po pup. This pop up will request content of confirm.php, and give us two main button as choise. “Yes” if delete confirmed and “No” id delete calceled.
So, we need action while delete button cilicked. Here the ajax request action:
//Handle the 'actual' delete button:
$("#confirmDeleteButton").click(function() {
var url = $(this).attr('action');
$.ajax({
type: "POST",
url: url,
success: function() {
$.fn.colorbox.close();
}
});
return false;
});
//Handle the dialog cancel button:
$("#cancelDeleteButton").click(function() {
$.fn.colorbox.close();
return false;
});
And how about saving data? Don’t worry we will create this beautifull JS Code, to handle while Submit form clicked to send post data.
var dataString = $('#updateForm').serialize();
//alert (dataString);
$.ajax({
type: "POST",
url: url,
data: dataString,
success: function() {
$.fn.colorbox.close();
}
});
Before sending post data and request action URL from controller, you may create simple form validation:
var title = $('#title');
var content = $('#content');
var url = $('#updateForm').attr('action');
if (title.val()=='') {
alert('Title field is required');
title.focus();
return false;
}
if (content.val()=='') {
alert('Content field is required');
content.focus();
return false;
}
Well, this is just a variation, your next code will better than sample above.
OK! let’s try the result on browser. Happy coding!!
Popularity: 70% [?]
Hello my fox! Glad to see you today!If you love my tutorial, please chose any action from the left button.
4 Comments
This is a nice article..
Its very easy to understand ..
And this article is using to learn something about it..
Thanks a lot..!
nice article and I modify to upload file..
how do I upload a file with this article?
tutorial bagus. dr emi ya. orang lama dah senior. saran bagusnya buat “add edit delete search article dengan CI atau Ajax”
Just say it with fill the comment form.
My Friends Link
10001 Inspirasi 4w1n.Blogspot.Com Afial blog Afotsum.CO.NR Alfikry Blogspot Ancaran.Com Andrian.Blogdrive.Com AngsaRea AraZidsi Arteknindo.Com ArtheZoo.TK Articlecillin Belajar Gratis Blog Si Bochan BloGila_U2.Blogdrive.Com BOGIRO Book and Movie Review Can_Dra Blog Catalog-Tutorial CatatanLou.110mb.Com Coin-Kevin DataBagus.Com Dede Permana, S. Kom (PT. BITA Bandung) Deniall.Com Desire 8 Distro & Clothing Diplomski.Com Ensept.Com Esato.Com Faris Wijaya FarisW.Com Blog Fendix Wordpress Foxxed-ART Gadget and Tech Gedex.Web.ID GejalaGila.Com GraphicVN HendiHen.Com Henny Indrianty Hmzaky-dot.Blogspot.Com I D I K IDWebHost.BIZ IDWebHost.Com Ilivetodesign.Com Ilmu Grafis Inez Nugroho Irenk Design IT Club Lombok Jafair.Multiply.Com Jaloe Blog Spot Jenggot Community JiranKubur Jurnal Jaloee K B M S Blog Klik-Kanan.Com LearnSimply LensaDarbi MadeInAra – Graphic Design Mark Xaviar Mifka.Multiply.Com More Tech Tips! Ngetixide.Wordpress.Com Nursingmedia.Blogspot.Com OneMoment.CO.NR PC MILD Percikan Iman Bandung Profit Trading Forex Pulsa Center PuwaSila Denpasar Rumah Sakit Herbal SEO Articles and Newsletters Seputar Info Wanita {Niella Anwar} SMKN 3 Batu Supermodel and Celebrity Tedy Blog TeguhNET Articles The-Sulton.Com TopBlogArea.Com Tutorial Flash – Blog Apri Tutorial Website Ubaid UdaraMaya.Com WebDesigner.Web.ID Yudha Yudhanto, S. KomAdvertise
Sponsors
Most Popular Posts
- Membuat Manajemen Hak Akses User dengan Codeigniter
- Interactive Ajax Data Management with Codeigniter
- Web Design Layout Plus Implementasi jQuery Tab Content
- Web Base Controller System with NirCMD
- Simple Swing Login Form And getText()
- dreLogin v.2.0 Has Release
- Create a simple application to open an EXE file on the window with JAVA
- Sony Ericsson Logo
- The Chain Tutorial from FuelYourCreativity
- Advance Metalic Gloss Logo
Category
Subcribe RSS Feed
Translate
Flick Group dr.emi
dr.emi creative design
SEO Articles & Newsletters
Forum dremi.info
Free Download
Recent Comments
- dr.emi: @ita : sekarng harus hati hati kalo penelpon nya dari hp reg...
- ita: saya juga hampir saja kena tipu untung saya cancel pengir...
- dr.emi: @al-k CUHUMUND =))...
- Loka Dwiartara: biasa kang orang mah udah nge-judge duluan, itu karena orang...
- zir: weeeesss manteb....
- dr.emi: @Mollie Colgate Thank you! This is my private theme for my w...
- Mollie Colgate: I really love your blog.. Pleasant colors & theme. Did y...
Recent Posts
- DISKON HARGA LISENSI WEBSEN 25%, PROMO HARI JADI DR.EMI CREATIVE DESIGN
- BJ HABIBIE - FIGUR ILMUWAN YANG SAYA KAGUMI
- JOKOWI Bukan Mencari Sensasi, Tapi Solusi!
- Sebuah penyemangat untuk saya dan semua orang
- Selamat Jalan Martoyo Umb
- Dremi.INFO spirit coming from these sentences
- Hasanain Juaeni - Tuan Guru, Tokoh Lombok, Peraih Ramon MagSaySay Award
- Ratna Sari Dewi Soekarno di Bukan Jalan Jalan Biasa TVONE (20 Jul 2012)
- Marjinal di TVOne - Salam Taring Babi!
- kenapa orang lain malas ngobrol sama kita? temukan jawabannya pada diri sndiri
Archives
Popular Tags
3D illustration abstract design adsense aero button animation banner clean navigation codeigniter colouring layer CSS tutorials effect finger print glassy effect google gradient style GUI photoshop design hacker handcoded HTML indonesian culture IT job jQuery layer mask logo lombok lowongan kerja merancang web pen tool photo retouch photoshop design PHP PHP Advance PHP login php programmer product demo relationship search engine shapping spirit text effect web articles web design web development web header web layout web tips




















PSD Files
PHP Source Code






