I think you'll agree if I say this:
“It is very difficult to create CRUD (Create Read Update Delete) application without reload page using Codeigniter and AJAX.”
Good News:
Well, It turns out, you can easily create CRUD application without reload page using Codeigniter and AJAX Jquery,
Right Now.!
This is the way I used a few months ago for my own project.
Today, in this tutorial, I will explain to you clearly how to make CRUD application without reload page using Codeigniter and Ajax Jquery.
STEP-BY-STEP!
What is AJAX?
AJAX (Asynchronous Javascript And XML) is a method or technique of web-based programming to create interactive web application.
With Ajax, Web applications can send and retrieve data from a server asynchronously (in the background) without interfering with the display and behavior of the existing page.
Pretty cool right?
In this tutorial, I use BOOTSTRAP modals to create input and update form.
BOOTSTRAP modals helps us make it easier to create CRUD(Create Read Update Delete) applications in just one page.
Awesome right?
Before bootstrap coming up, to make a CRUD application requires several pages.
There are page to display data from database, create form page, and edit form page.
OK, Let’s get start it!
Step 1. Preparation
This is important!
If you missed this step, it means you missed the whole of this tutorial.
Good preparation will determine your success following this tutorial. The better your preparation, the more likely you will succeed in following this tutorial.
Do not skip this step, though it feels complex.
So, what do you need to prepare?
Here’s the list:
1. Codeigniter
Codeigniter is the main php framework we will use in this tutorial. If you do not have it yet, please download it at the official website:
2. Bootstrap
Bootstrap is a framework to beautify the user interface (UI). If you do not have it yet, please download it first at the official website:
3. Jquery
This is important!
Jquery is a javascript framework that works to help simplify the writing of AJAX-based scripts.
If you do not have it yet, please download it first at the official website:
4. Datatables
Datatables is a plugin built from jquery to display data in table form and has integrated with filters, show per page, and pagination.
To download datatables please download at following link: https://datatables.net/download/index.
Ok, Let's continue!
Step 2. Creating of database structures
In this tutorial, I use mysql as Database Management System (DBMS).
If you also use mysql, you will love this tutorial.
But,
If you are using other DBMS like Oracle, SQL Server, Maria DB, or MongoDB.
No, Problem!
Provided you understand SQL (Structured Query Language) better.
Ok, Let's continue!
Please create a database, here I create a database with name db_crud.
If you create a database with the same name it will be better.
Please execute this query to create the database:
CREATE DATABASE db_crud;
That query will generate a database with name db_crud.
After that,
Create a table with name product with structure like this:
To create a table with structure like that,
Please execute this query:
CREATE TABLE product( product_code varchar(15) PRIMARY KEY, product_name VARCHAR(100), product_price INT(11) )ENGINE=INNODB;
Step 3. Setup Codeigniter
Extract codeigniter that has been downloaded earlier to www folder (if you use wampserver) or htdocs (if you use XAMPP).
Because I use wampserver. So, I extract it to c:/wamp/www/
And then, rename codeigniter project to be crud_ajax.
Like this:
Open crud_ajax folder and create assets folder. And then include the bootstrap, datatables, and jquery files inside the assets folder.
So that look like this:
Step 4. Configuration Codeigniter
Next step is the configuration on the codeigniter.
Here are some files you need to configure:
1. Autoload.php
To configure the autoload.php, please open the folder:
application/config/autoload.php
like this:
Open autoload.php using text editor like Notepad++ or Sublime Text.
And then find this code:
$autoload['libraries'] = array(); $autoload['helper'] = array();
Set to be like this:
$autoload['libraries'] = array('database'); $autoload['helper'] = array('url');
2. Config.php
To configure the config.php, please open the folder:
application/config/config.php
like this:
Open config.php file using text editor, and then find this code:
$config['base_url'] = '';
Set to be like this:
$config['base_url'] = 'http://localhost/crud_ajax/';
3. Database.php
To configure the database.php, please open the folder:
application/config/database.php
like this:
Open database.php file using text editor, and then find this code:
$active_group = 'default'; $query_builder = TRUE; $db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => '', 'password' => '', 'database' => '', 'dbdriver' => 'mysqli', 'dbprefix' => '', 'pconnect' => FALSE, 'db_debug' => (ENVIRONMENT !== 'production'), 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8', 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array(), 'save_queries' => TRUE );
Set to be like this:
$active_group = 'default'; $query_builder = TRUE; $db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'db_crud', 'dbdriver' => 'mysqli', 'dbprefix' => '', 'pconnect' => FALSE, 'db_debug' => (ENVIRONMENT !== 'production'), 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8', 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array(), 'save_queries' => TRUE );
Step 5. Controller
Go ahead and create a controller file controllers/Product.php with the following this code:
<?php class Product extends CI_Controller{ function __construct(){ parent::__construct(); $this->load->model('product_model'); } function index(){ $this->load->view('product_view'); } function product_data(){ $data=$this->product_model->product_list(); echo json_encode($data); } function save(){ $data=$this->product_model->save_product(); echo json_encode($data); } function update(){ $data=$this->product_model->update_product(); echo json_encode($data); } function delete(){ $data=$this->product_model->delete_product(); echo json_encode($data); } }
Step 6. Model
Go ahead and create a model file models/Product_model.php with the following this code:
<?php class Product_model extends CI_Model{ function product_list(){ $hasil=$this->db->get('product'); return $hasil->result(); } function save_product(){ $data = array( 'product_code' => $this->input->post('product_code'), 'product_name' => $this->input->post('product_name'), 'product_price' => $this->input->post('price'), ); $result=$this->db->insert('product',$data); return $result; } function update_product(){ $product_code=$this->input->post('product_code'); $product_name=$this->input->post('product_name'); $product_price=$this->input->post('price'); $this->db->set('product_name', $product_name); $this->db->set('product_price', $product_price); $this->db->where('product_code', $product_code); $result=$this->db->update('product'); return $result; } function delete_product(){ $product_code=$this->input->post('product_code'); $this->db->where('product_code', $product_code); $result=$this->db->delete('product'); return $result; } }
Step 7. View
Go ahead and create a view file views/product_view.php with the following this code:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Product List</title> <link rel="stylesheet" type="text/css" href="<?php echo base_url().'assets/css/bootstrap.css'?>"> <link rel="stylesheet" type="text/css" href="<?php echo base_url().'assets/css/jquery.dataTables.css'?>"> <link rel="stylesheet" type="text/css" href="<?php echo base_url().'assets/css/dataTables.bootstrap4.css'?>"> </head> <body> <div class="container"> <!-- Page Heading --> <div class="row"> <div class="col-12"> <div class="col-md-12"> <h1>Product <small>List</small> <div class="float-right"><a href="javascript:void(0);" class="btn btn-primary" data-toggle="modal" data-target="#Modal_Add"><span class="fa fa-plus"></span> Add New</a></div> </h1> </div> <table class="table table-striped" id="mydata"> <thead> <tr> <th>Product Code</th> <th>Product Name</th> <th>Price</th> <th style="text-align: right;">Actions</th> </tr> </thead> <tbody id="show_data"> </tbody> </table> </div> </div> </div> <!-- MODAL ADD --> <form> <div class="modal fade" id="Modal_Add" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Add New Product</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <div class="form-group row"> <label class="col-md-2 col-form-label">Product Code</label> <div class="col-md-10"> <input type="text" name="product_code" id="product_code" class="form-control" placeholder="Product Code"> </div> </div> <div class="form-group row"> <label class="col-md-2 col-form-label">Product Name</label> <div class="col-md-10"> <input type="text" name="product_name" id="product_name" class="form-control" placeholder="Product Name"> </div> </div> <div class="form-group row"> <label class="col-md-2 col-form-label">Price</label> <div class="col-md-10"> <input type="text" name="price" id="price" class="form-control" placeholder="Price"> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" type="submit" id="btn_save" class="btn btn-primary">Save</button> </div> </div> </div> </div> </form> <!--END MODAL ADD--> <!-- MODAL EDIT --> <form> <div class="modal fade" id="Modal_Edit" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Edit Product</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <div class="form-group row"> <label class="col-md-2 col-form-label">Product Code</label> <div class="col-md-10"> <input type="text" name="product_code_edit" id="product_code_edit" class="form-control" placeholder="Product Code" readonly> </div> </div> <div class="form-group row"> <label class="col-md-2 col-form-label">Product Name</label> <div class="col-md-10"> <input type="text" name="product_name_edit" id="product_name_edit" class="form-control" placeholder="Product Name"> </div> </div> <div class="form-group row"> <label class="col-md-2 col-form-label">Price</label> <div class="col-md-10"> <input type="text" name="price_edit" id="price_edit" class="form-control" placeholder="Price"> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" type="submit" id="btn_update" class="btn btn-primary">Update</button> </div> </div> </div> </div> </form> <!--END MODAL EDIT--> <!--MODAL DELETE--> <form> <div class="modal fade" id="Modal_Delete" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Delete Product</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <strong>Are you sure to delete this record?</strong> </div> <div class="modal-footer"> <input type="hidden" name="product_code_delete" id="product_code_delete" class="form-control"> <button type="button" class="btn btn-secondary" data-dismiss="modal">No</button> <button type="button" type="submit" id="btn_delete" class="btn btn-primary">Yes</button> </div> </div> </div> </div> </form> <!--END MODAL DELETE--> <script type="text/javascript" src="<?php echo base_url().'assets/js/jquery-3.2.1.js'?>"></script> <script type="text/javascript" src="<?php echo base_url().'assets/js/bootstrap.js'?>"></script> <script type="text/javascript" src="<?php echo base_url().'assets/js/jquery.dataTables.js'?>"></script> <script type="text/javascript" src="<?php echo base_url().'assets/js/dataTables.bootstrap4.js'?>"></script> <script type="text/javascript"> $(document).ready(function(){ show_product(); //call function show all product $('#mydata').dataTable(); //function show all product function show_product(){ $.ajax({ type : 'ajax', url : '<?php echo site_url('product/product_data')?>', async : true, dataType : 'json', success : function(data){ var html = ''; var i; for(i=0; i<data.length; i++){ html += '<tr>'+ '<td>'+data[i].product_code+'</td>'+ '<td>'+data[i].product_name+'</td>'+ '<td>'+data[i].product_price+'</td>'+ '<td style="text-align:right;">'+ '<a href="javascript:void(0);" class="btn btn-info btn-sm item_edit" data-product_code="'+data[i].product_code+'" data-product_name="'+data[i].product_name+'" data-price="'+data[i].product_price+'">Edit</a>'+' '+ '<a href="javascript:void(0);" class="btn btn-danger btn-sm item_delete" data-product_code="'+data[i].product_code+'">Delete</a>'+ '</td>'+ '</tr>'; } $('#show_data').html(html); } }); } //Save product $('#btn_save').on('click',function(){ var product_code = $('#product_code').val(); var product_name = $('#product_name').val(); var price = $('#price').val(); $.ajax({ type : "POST", url : "<?php echo site_url('product/save')?>", dataType : "JSON", data : {product_code:product_code , product_name:product_name, price:price}, success: function(data){ $('[name="product_code"]').val(""); $('[name="product_name"]').val(""); $('[name="price"]').val(""); $('#Modal_Add').modal('hide'); show_product(); } }); return false; }); //get data for update record $('#show_data').on('click','.item_edit',function(){ var product_code = $(this).data('product_code'); var product_name = $(this).data('product_name'); var price = $(this).data('price'); $('#Modal_Edit').modal('show'); $('[name="product_code_edit"]').val(product_code); $('[name="product_name_edit"]').val(product_name); $('[name="price_edit"]').val(price); }); //update record to database $('#btn_update').on('click',function(){ var product_code = $('#product_code_edit').val(); var product_name = $('#product_name_edit').val(); var price = $('#price_edit').val(); $.ajax({ type : "POST", url : "<?php echo site_url('product/update')?>", dataType : "JSON", data : {product_code:product_code , product_name:product_name, price:price}, success: function(data){ $('[name="product_code_edit"]').val(""); $('[name="product_name_edit"]').val(""); $('[name="price_edit"]').val(""); $('#Modal_Edit').modal('hide'); show_product(); } }); return false; }); //get data for delete record $('#show_data').on('click','.item_delete',function(){ var product_code = $(this).data('product_code'); $('#Modal_Delete').modal('show'); $('[name="product_code_delete"]').val(product_code); }); //delete record to database $('#btn_delete').on('click',function(){ var product_code = $('#product_code_delete').val(); $.ajax({ type : "POST", url : "<?php echo site_url('product/delete')?>", dataType : "JSON", data : {product_code:product_code}, success: function(data){ $('[name="product_code_delete"]').val(""); $('#Modal_Delete').modal('hide'); show_product(); } }); return false; }); }); </script> </body> </html>
Now, go ahead and access our custom page at http://localhost/crud_ajax/index.php/product and you will see the final result like this:
So, that's it,
We've done it!
Please click add new button to add new product, click edit button to update record, and click delete button to delete record.
Congratulations!
You did it. Now, you can create a crud application without reloading the page with codeigniter and ajax.
If you feel this tutorial is useful for you. Please share! Perhaps, this tutorial is useful also for your friend!
Thank you very much.
Recommended for you:
#1. Dynamic Select Options Dependent Dropdown in Codeigniter and Ajax
#2. How to Create a Shopping Cart Using Codeigniter and Ajax [FULL TUTORIAL]
#3. How to Upload files using Codeigniter and Ajax [Complete Tutorial]
Download Source on Github
Comments (40)
Lasse, 03 February 2018 02:35 -
Hi. Followed your little tutorial here, and cannot get it to display my table. It is showing a error: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience." This can be handled by setting "async: true". But changing this does not get it to show my table. When I press add, and fill out the form, the data is sent to the table. But as soon as it displays the main site, it just says "No data available in table"
M Fikri, 08 February 2018 07:32 -
Actually, This tutorial already tested. Perhaps, there are something miss.
I recommend you to download the source code, and learn from that.
Thank you for your response.!
motaz, 25 February 2018 15:37 -
Thanks
M Fikri, 27 February 2018 04:51 -
You are welcome!
naz jonson, 14 March 2018 13:38 -
We have update list of do-follow blog commenting sites for new visitors, we will update this list regular basis so share our list to your friends also. <a href="http://www.sthint.com/2017/11/17/100-instant-approval-free-dofollow-blog-commenting-sites-list-2018/">the bookmarking sites</a>
YIKFOO, 14 April 2018 17:31 -
Thanks,it very useful for me. Sir, can i ask a question, I updated the product data but the datatable did not reload.The below entries message and the searching function did not reload. I can't searching the new updated information and see the accurate entries message. Can teach me how to ajax reload datatables?
YIKFOO, 14 April 2018 17:38 -
Thanks sir, It tutorial very useful for me. Can i ask a question ? I added product but the datatable did not reload. The datatable searching function cant search the new added information and velow entries message also did not update. Can teach me how to using ajax reload datatable?
M Fikri, 22 April 2018 08:08 -
Hi Yikfoo, thanks for your response.
Actually, you need to reload the whole page for that.
you can use:
location.reload();
Daria Setsova, 16 April 2018 21:35 -
Nice Post!
M Fikri, 22 April 2018 08:08 -
Thank You!
Abhishek, 14 June 2018 06:40 -
Great post. But the error persists. Even after downloading your files. It is showing a error: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. How should I proceed now ?
Rishi, 21 June 2018 11:14 -
when i alert(data.length) show in alert object object How can i resolve this error i want to alert all colums value
SlceCut, 27 June 2018 02:12 -
i want to open another page for update and delete not in model what can i do>??
Nixpatel, 28 June 2018 09:26 -
It's nice sir, But can tell me about validation in ci using ajax or js ?? Or can you share tutorial about that in detail ? So I can easily learn. Thank you sir
smudge, 29 June 2018 18:52 -
you made it simple!!!!
M Fikri, 21 November 2018 11:16 -
Thank You.
lakshmi narayanan, 29 June 2018 20:09 -
thank you..! (please to change default_controller as an->Product) awesome code.
M Fikri, 13 August 2018 10:00 -
Good Advice, Thanks
Hamid, 21 July 2018 22:24 -
It's nice and simple! Thanks
M Fikri, 13 August 2018 10:01 -
You're welcome.
Xtrainer, 12 August 2018 17:50 -
Hi sir, firstly thank you for this useful tutorial, then i can get data using ajax
M Fikri, 13 August 2018 10:01 -
You're welcome sir.
Javier, 02 November 2018 13:35 -
You could help me, if I delete the file 'index.php in the config file, then I do not get the information, I get that there is no data
M Fikri, 21 November 2018 11:15 -
I recomend you to use site_url() to fix the problem.
Basil George, 01 February 2019 14:47 -
i likeed your article about AJAX with Codeigniter.it helped me a lot.Thank you very much
M Fikri, 07 February 2019 21:45 -
Basil George, You are welcome.
Ramakanta Chandra, 07 February 2019 21:38 -
Thank you. It's working
M Fikri, 07 February 2019 21:41 -
You are welcome, Ramakanta Chandra
Abhi , 27 September 2021 23:02 -
In delete data code you make a selector with id.. and there is not any id is defined in delete button. you define a calls. Is it ok..??