Creating a CRUD Web App using CodeIgniter, jQuery, and Ajax Tutorial

Language

In this tutorial, we will tackle how to create a simple web application with a CRUD (Create, Read, Update, and Delete) Operations using CodeIgniter Framework. The CodeIgniter is a PHP Framework use in building dynamic web applications or websites with PHP. Our main goal in this tutorial is to develop an App that contains an Add/Edit Form, Display Data, and Delete Data.

Before we start, please download and install a local web server such as XAMPP/WAMP to run our PHP scripts. In my case, I will be using XAMPP. After the installation. kindly open your XAMPP/WAMP's Control Panel and start Apache and MySQL. Then, download the CodeInigter 3 and extract it. Move the extracted folder inside the "htdocs" for XAMPP and "www" for WAMP.

I will be using Bootstrap and jQuery for the User Interface of the web application.

So, Let's get Started...

Creating the database

  1. Open a web browser and browse the PHPMyAdmin i.e. http://localhost/phpmyadmin
  2. Create a new database naming codeigniter
  3. Copy the SQL Script below and paste it in the SQL Tab of your PHPMyAdmin and click the Go Button.
  1. CREATE TABLE `users` (
  2. `email` varchar(40) NOT NULL,
  3. `password` varchar(40) NOT NULL,
  4. `fname` varchar(100) NOT NULL

You can also use the provided SQL File, along with the working source code zip file. The file is known as codeigniter.sql and located inside the db folder.

Configuring the CodeIgniter

Locate the config file of the codeigniter and configure the base_url. The file is known as config.php and located insdide the application/config directory.

Example
  1. $config['base_url'] = 'http://localhost/sourcecodester/codeigniter_crud_ajax';

Configuring the Database Connection

Open the database.phpfile located inside the application/config directory and follow configuration below.

  1. $db['default'] = array(
  2. 'dsn' => '',
  3. 'hostname' => 'localhost',
  4. 'username' => 'root',
  5. 'password' => '',
  6. 'database' => 'codeigniter',
  7. 'dbdriver' => 'mysqli',
  8. 'dbprefix' => '',
  9. 'pconnect' => TRUE,
  10. 'db_debug' => (ENVIRONMENT !== 'production'),
  11. 'cache_on' => FALSE,
  12. 'cachedir' => '',
  13. 'char_set' => 'utf8',
  14. 'dbcollat' => 'utf8_general_ci',
  15. 'swap_pre' => '',
  16. 'encrypt' => FALSE,
  17. 'compress' => FALSE,
  18. 'stricton' => FALSE,
  19. 'failover' => array(),
  20. 'save_queries' => TRUE
  21. );

Creating the .htaccess file

This file will remove the .htaccess in the URL.

  1. <IfModule mod_rewrite.c>
  2. RewriteEngine On
  3. RewriteCond %{REQUEST_FILENAME} !-f
  4. RewriteCond %{REQUEST_FILENAME} !-d
  5. RewriteRule ^(.*)$ index.php/$1 [L]
  6. </IfModule>

Creating the App Controller

Create a new php file inside the application/controller directory. Copy/Paste the script below and save it as User.php.

  1. <?php
  2. defined('BASEPATH') OR exit('No direct script access allowed');
  3.  
  4. class User extends CI_Controller {
  5.  
  6. function __construct(){
  7. parent::__construct();
  8. $this->load->helper('url');
  9. $this->load->model('users_model');
  10. //include modal.php in views
  11. $this->inc['modal'] = $this->load->view('modal', '', true);
  12. }
  13. public function index(){
  14. $this->load->view('show', $this->inc);
  15. }
  16.  
  17. public function show(){
  18. $data = $this->users_model->show();
  19. $output = array();
  20. foreach($data as $row){
  21. ?>
  22. <tr>
  23. <td><?php echo $row->id; ?></td>
  24. <td><?php echo $row->email; ?></td>
  25. <td><?php echo $row->password; ?></td>
  26. <td><?php echo $row->fname; ?></td>
  27. <td>
  28. <button class="btn btn-warning edit" data-id="<?php echo $row->id; ?>"><span class="glyphicon glyphicon-edit"></span> Edit</button> ||
  29. <button class="btn btn-danger delete" data-id="<?php echo $row->id; ?>"><span class="glyphicon glyphicon-trash"></span> Delete</button>
  30. </td>
  31. </tr>
  32. <?php
  33. }
  34. }
  35.  
  36. public function insert(){
  37. $user['email'] = $_POST['email'];
  38. $user['password'] = $_POST['password'];
  39. $user['fname'] = $_POST['fname'];
  40.  
  41. $query = $this->users_model->insert($user);
  42. }
  43.  
  44. public function getuser(){
  45. $id = $_POST['id'];
  46. $data = $this->users_model->getuser($id);
  47. echo json_encode($data);
  48. }
  49.  
  50. public function update(){
  51. $id = $_POST['id'];
  52. $user['email'] = $_POST['email'];
  53. $user['password'] = $_POST['password'];
  54. $user['fname'] = $_POST['fname'];
  55.  
  56. $query = $this->users_model->updateuser($user, $id);
  57. }
  58.  
  59. public function delete(){
  60. $id = $_POST['id'];
  61. $query = $this->users_model->delete($id);
  62. }
  63.  
  64. }

Chnage the default application's controller to user. To do this, kindly open the routes.php file inside the application/config directory.

  1. $route['default_controller'] = 'user';
  2. $route['404_override'] = '';
  3. $route['translate_uri_dashes'] = FALSE;

Creating the Application Model

The script below contains the code that queries the data from/to the database. To create the file, create a new php file inside the application/models directory and save it as User_model.php. Then, copy/paste the code below.

  1. <?php
  2. class Users_model extends CI_Model {
  3. function __construct(){
  4. parent::__construct();
  5. $this->load->database();
  6. }
  7.  
  8. public function show(){
  9. $query = $this->db->get('users');
  10. return $query->result();
  11. }
  12.  
  13. public function insert($user){
  14. return $this->db->insert('users', $user);
  15. }
  16.  
  17. public function getuser($id){
  18. $query = $this->db->get_where('users',array('id'=>$id));
  19. return $query->row_array();
  20. }
  21.  
  22. public function updateuser($user, $id){
  23. $this->db->where('users.id', $id);
  24. return $this->db->update('users', $user);
  25. }
  26.  
  27. public function delete($id){
  28. $this->db->where('users.id', $id);
  29. return $this->db->delete('users');
  30. }
  31.  
  32. }
  33. ?>

Creating the Interface

The following codes are the scripts of our user interface that displays the data, add/edit form, and the delete confirmation modal. Save the file accordingly inisde the aplication/views directory.

show.php
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>CodeIgniter Ajax CRUD using jQuery</title>
  6. <link rel="stylesheet" href="<?php echo base_url(); ?>bootstrap/css/bootstrap.min.css">
  7. <script src="<?php echo base_url(); ?>jquery/jquery.min.js"></script>
  8. <script src="<?php echo base_url(); ?>bootstrap/js/bootstrap.min.js"></script>
  9. </head>
  10. <body>
  11. <div class="container">
  12. <h1 class="page-header text-center">CodeIgniter Ajax CRUD using jQuery</h1>
  13. <div class="row">
  14. <div class="col-sm-8 col-sm-offset-2">
  15. <button class="btn btn-primary" id="add"><span class="glyphicon glyphicon-plus"></span> Add New</button>
  16. <table class="table table-bordered table-striped" style="margin-top:20px;">
  17. <thead>
  18. <tr>
  19. <th>ID</th>
  20. <th>Email</th>
  21. <th>Password</th>
  22. <th>FullName</th>
  23. <th>Action</th>
  24. </tr>
  25. </thead>
  26. <tbody id="tbody">
  27. </tbody>
  28. </table>
  29. </div>
  30. </div>
  31. <?php echo $modal; ?>
  32.  
  33. <script type="text/javascript">
  34. $(document).ready(function(){
  35. //create a global variable for our base url
  36. var url = '<?php echo base_url(); ?>';
  37.  
  38. //fetch table data
  39. showTable();
  40.  
  41. //show add modal
  42. $('#add').click(function(){
  43. $('#addnew').modal('show');
  44. $('#addForm')[0].reset();
  45. });
  46.  
  47. //submit add form
  48. $('#addForm').submit(function(e){
  49. e.preventDefault();
  50. var user = $('#addForm').serialize();
  51. $.ajax({
  52. type: 'POST',
  53. url: url + 'user/insert',
  54. data: user,
  55. success:function(){
  56. $('#addnew').modal('hide');
  57. showTable();
  58. }
  59. });
  60. });
  61.  
  62. //show edit modal
  63. $(document).on('click', '.edit', function(){
  64. var id = $(this).data('id');
  65. $.ajax({
  66. type: 'POST',
  67. url: url + 'user/getuser',
  68. dataType: 'json',
  69. data: {id: id},
  70. success:function(response){
  71. console.log(response);
  72. $('#email').val(response.email);
  73. $('#password').val(response.password);
  74. $('#fname').val(response.fname);
  75. $('#userid').val(response.id);
  76. $('#editmodal').modal('show');
  77. }
  78. });
  79. });
  80.  
  81. //update selected user
  82. $('#editForm').submit(function(e){
  83. e.preventDefault();
  84. var user = $('#editForm').serialize();
  85. $.ajax({
  86. type: 'POST',
  87. url: url + 'user/update',
  88. data: user,
  89. success:function(){
  90. $('#editmodal').modal('hide');
  91. showTable();
  92. }
  93. });
  94. });
  95.  
  96. //show delete modal
  97. $(document).on('click', '.delete', function(){
  98. var id = $(this).data('id');
  99. $.ajax({
  100. type: 'POST',
  101. url: url + 'user/getuser',
  102. dataType: 'json',
  103. data: {id: id},
  104. success:function(response){
  105. console.log(response);
  106. $('#delfname').html(response.fname);
  107. $('#delid').val(response.id);
  108. $('#delmodal').modal('show');
  109. }
  110. });
  111. });
  112.  
  113. $('#delid').click(function(){
  114. var id = $(this).val();
  115. $.ajax({
  116. type: 'POST',
  117. url: url + 'user/delete',
  118. data: {id: id},
  119. success:function(){
  120. $('#delmodal').modal('hide');
  121. showTable();
  122. }
  123. });
  124. });
  125.  
  126. });
  127.  
  128. function showTable(){
  129. var url = '<?php echo base_url(); ?>';
  130. $.ajax({
  131. type: 'POST',
  132. url: url + 'user/show',
  133. success:function(response){
  134. $('#tbody').html(response);
  135. }
  136. });
  137. }
  138. </script>
  139. </div>
  140. </body>
  141. </html>
modal.php
  1. <!-- Add New -->
  2. <div class="modal fade" id="addnew" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  3. <div class="modal-dialog">
  4. <div class="modal-content">
  5. <div class="modal-header">
  6. <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
  7. <center><h4 class="modal-title" id="myModalLabel">Add New Member</h4></center>
  8. </div>
  9. <div class="modal-body">
  10. <div class="container-fluid">
  11. <form id="addForm">
  12. <div class="row">
  13. <div class="col-md-3">
  14. <label class="control-label" style="position:relative; top:7px;">Email:</label>
  15. </div>
  16. <div class="col-md-9">
  17. <input type="email" class="form-control" name="email" required>
  18. </div>
  19. </div>
  20. <div style="height:10px;"></div>
  21. <div class="row">
  22. <div class="col-md-3">
  23. <label class="control-label" style="position:relative; top:7px;">Password:</label>
  24. </div>
  25. <div class="col-md-9">
  26. <input type="password" class="form-control" name="password" required>
  27. </div>
  28. </div>
  29. <div style="height:10px;"></div>
  30. <div class="row">
  31. <div class="col-md-3">
  32. <label class="control-label" style="position:relative; top:7px;">Full Name:</label>
  33. </div>
  34. <div class="col-md-9">
  35. <input type="text" class="form-control" name="fname" required>
  36. </div>
  37. </div>
  38. </div>
  39. </div>
  40. <div class="modal-footer">
  41. <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
  42. <button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Save</a>
  43. </form>
  44. </div>
  45.  
  46. </div>
  47. </div>
  48. </div>
  49.  
  50. <!-- Edit -->
  51. <div class="modal fade" id="editmodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  52. <div class="modal-dialog">
  53. <div class="modal-content">
  54. <div class="modal-header">
  55. <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
  56. <center><h4 class="modal-title" id="myModalLabel">Edit Member</h4></center>
  57. </div>
  58. <div class="modal-body">
  59. <div class="container-fluid">
  60. <form id="editForm">
  61. <div class="row">
  62. <div class="col-md-3">
  63. <label class="control-label" style="position:relative; top:7px;">Email:</label>
  64. </div>
  65. <div class="col-md-9">
  66. <input type="text" class="form-control" name="email" id="email">
  67. </div>
  68. </div>
  69. <div style="height:10px;"></div>
  70. <div class="row">
  71. <div class="col-md-3">
  72. <label class="control-label" style="position:relative; top:7px;">Password:</label>
  73. </div>
  74. <div class="col-md-9">
  75. <input type="text" class="form-control" name="password" id="password">
  76. </div>
  77. </div>
  78. <div style="height:10px;"></div>
  79. <div class="row">
  80. <div class="col-md-3">
  81. <label class="control-label" style="position:relative; top:7px;">Full Name:</label>
  82. </div>
  83. <div class="col-md-9">
  84. <input type="text" class="form-control" name="fname" id="fname">
  85. </div>
  86. </div>
  87. <input type="hidden" name="id" id="userid">
  88. </div>
  89. </div>
  90. <div class="modal-footer">
  91. <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
  92. <button type="submit" class="btn btn-warning"><span class="glyphicon glyphicon-check"></span> Update</a>
  93. </form>
  94. </div>
  95.  
  96. </div>
  97. </div>
  98. </div>
  99.  
  100. <!-- Delete -->
  101. <div class="modal fade" id="delmodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  102. <div class="modal-dialog">
  103. <div class="modal-content">
  104. <div class="modal-header">
  105. <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
  106. <center><h4 class="modal-title" id="myModalLabel">Delete Member</h4></center>
  107. </div>
  108. <div class="modal-body">
  109. <h4 class="text-center">Are you sure you want to delete</h4>
  110. <h2 id="delfname" class="text-center"></h2>
  111. </div>
  112. <div class="modal-footer">
  113. <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
  114. <button type="button" id="delid" class="btn btn-danger"><span class="glyphicon glyphicon-trash"></span> Yes</button>
  115. </div>
  116.  
  117. </div>
  118. </div>
  119. </div>

DEMO

That's it! You can now test the web application in a browser by browsing i.e. http://localhost/[source code folder name]. That's the end of this tutorial. I hope this tutorial will help you with what you are looking for and will be useful for your future PHP/Codeigniter Projects.

Explore more on this website for more Free Source Codes and Tutorials.

Happy Coding :)

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Comments

Add new comment