Codeigniter CRUD Operation With Ajax Example
In this tutorial, We will inform you how to perform crud operation with ajax in CodeIgniter.
CRUD stands for create, read, update, and delete. if you create a user-friendly website at that time need to crud operation.
if you want to create CRUD operation with ajax in CodeIgniter, then the first configuration of the database and connect the MySQL database then after creating CRUD operation with ajax in Codeigniter.
in our post through, We will go how to connect CodeIgniter to MySQL and perform the CRUD operation.
Overview
Step 1: Download and install Codeigniter
Step 2: Create a Database in table
Step 3: Connect to Database
Step 4: Create Controller
Step 5: Create a Model
Step 6: Create View File
Step 1: Download and install Codeigniter
We are going to install Codeigniter 3, first, we will download a fresh Codeigniter 3 version and install it in our system. so you can follow below Link for Download CodeIgniter.
Step 2: Create a Database in table
In this step, we have to create a table in the database, so we will create a database using the below code.
1 2 3 4 5 6 7 | CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(64) NOT NULL, `last_name` varchar(64) NOT NULL, `address` text NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ; |
Step 3: Connect to Database
Go to the config folder and open database.php file some changes in this file like hostname, database username, database password, and database name.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | $db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'enter here database name', '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 4: Create Controller
In this step, we will create an Ajax_crud.php file in the “application/controller” directory and paste the below code in this controller.
application/controller/Ajax_crud.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Ajax_crud extends CI_Controller { /** * Constructor of Controller * * @return Response */ public function __construct() { parent::__construct(); $this->load->model('common_model'); } public function index() { $arrData['user_details'] = $this->common_model->get_all_users(); $this->load->view('ajax_crud/list',$arrData); } public function add() { $arrData['first_name'] = $this->input->post('txtFirstName'); $arrData['last_name'] = $this->input->post('txtLastName'); $arrData['address'] = $this->input->post('txtAddress'); $arrData['created'] = date('Y-m-d H:i:s'); $insert= $this->common_model->get_last_inserted_id('users',$arrData); if($insert != false) { $data = $this->common_model->get_row('users',array('id' =>$insert)); echo json_encode(array("status" => true , 'data' => $data)); } else{ echo json_encode(array("status" => false , 'data' => $data)); } } public function edit($id) { $data = $this->common_model->get_row('users',array('id' =>$id)); if($data){ echo json_encode(array("status" => true , 'data' => $data)); }else{ echo json_encode(array("status" => false)); } } public function update() { $id = $this->input->post('hdnUserId'); $editData['first_name'] = $this->input->post('txtFirstName'); $editData['last_name'] = $this->input->post('txtLastName'); $editData['address'] = $this->input->post('txtAddress'); $update= $this->common_model->update('users',array('id' =>$id),$editData); if($update != false) { $data = $this->common_model->get_row('users',array('id' =>$id)); echo json_encode(array("status" => true , 'data' => $data)); } else{ echo json_encode(array("status" => false , 'data' => $data)); } } public function delete($id) { $delete=$this->common_model->delete_data('users',array('id' =>$id)); if($delete) { echo json_encode(array("status" => true)); }else{ echo json_encode(array("status" => false)); } } } ?> |
Step 5: Create a Model
In this step, we will create a Common_model.php file in the “application/models” directory and paste the below code in this model.
application/models/Common_model.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Common_model extends CI_Model { public function __construct() { parent::__construct(); $this->load->database(); } public function get_all_users() { $this->db->select('*'); $this->db->from('users'); $this->db->order_by('id','desc'); $objQuery = $this->db->get(); return $objQuery->result_array(); } public function get_last_inserted_id($table,$data) { if($this->db->insert($table,$data)) { return $this->db->insert_id(); } else { return false; } } public function get_row($table,$where) { $this->db->from($table); $this->db->where($where); $query = $this->db->get(); return $query->row(); } public function update($table,$where_array,$data) { $this->db->where($where_array); if($this->db->update($table,$data)) { return true; } else { return false; } } public function delete_data($table,$where) { if($this->db->delete($table,$where)) { return true; } else { return false; } } } ?> |
Step 6: Create View File
So finally, we will create the autocomplete.php file in the “application/views/ajax_crud/” directory.
application/views/ajax_crud/list.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 | <!DOCTYPE html> <html lang="en"> <head> <title>Codeigniter CRUD Operation With Ajax Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-lg-11"> <h2>Codeigniter 3 Ajax CRUD Example</h2> </div> <div class="col-lg-1"> <a class="btn btn-success" href="#" data-toggle="modal" data-target="#addModal">Add</a> </div> </div> <table class="table table-bordered" id="userTable"> <thead> <tr> <th>id</th> <th>First Name</th> <th>Last Name</th> <th>Address</th> <th width="280px">Action</th> </tr> </thead> <tbody> <?php foreach($user_details as $row){ ?> <tr id="<?php echo $row['id']; ?>"> <td><?php echo $row['id']; ?></td> <td><?php echo $row['first_name']; ?></td> <td><?php echo $row['last_name']; ?></td> <td><?php echo $row['address']; ?></td> <td> <a data-id="<?php echo $row['id']; ?>" class="btn btn-primary btnEdit">Edit</a> <a data-id="<?php echo $row['id']; ?>" class="btn btn-danger btnDelete">Delete</a> </td> </tr> <?php } ?> </tbody> </table> <!-- Add User Modal --> <div id="addModal" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- User Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h4 class="modal-title">Add New User</h4> </div> <div class="modal-body"> <form id="addUser" name="addUser" action="<?php echo base_url(); ?>ajax_crud/add" method="post"> <div class="form-group"> <label for="txtFirstName">First Name:</label> <input type="text" class="form-control" id="txtFirstName" placeholder="Enter First Name" name="txtFirstName"> </div> <div class="form-group"> <label for="txtLastName">Last Name:</label> <input type="text" class="form-control" id="txtLastName" placeholder="Enter Last Name" name="txtLastName"> </div> <div class="form-group"> <label for="txtAddress">Address:</label> <textarea class="form-control" id="txtAddress" name="txtAddress" rows="10" placeholder="Enter Address"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!-- Update User Modal --> <div id="updateModal" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- User Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h4 class="modal-title">Update User</h4> </div> <div class="modal-body"> <form id="updateUser" name="updateUser" action="<?php echo base_url(); ?>ajax_crud/update" method="post"> <input type="hidden" name="hdnUserId" id="hdnUserId"/> <div class="form-group"> <label for="txtFirstName">First Name:</label> <input type="text" class="form-control" id="txtFirstName" placeholder="Enter First Name" name="txtFirstName"> </div> <div class="form-group"> <label for="txtLastName">Last Name:</label> <input type="text" class="form-control" id="txtLastName" placeholder="Enter Last Name" name="txtLastName"> </div> <div class="form-group"> <label for="txtAddress">Address:</label> <textarea class="form-control" id="txtAddress" name="txtAddress" rows="10" placeholder="Enter Address"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> <script> $(document).ready(function () { //Add the User $("#addUser").validate({ rules: { txtFirstName: "required", txtLastName: "required", txtAddress: "required" }, messages: { }, submitHandler: function(form) { var form_action = $("#addUser").attr("action"); $.ajax({ data: $('#addUser').serialize(), url: form_action, type: "POST", dataType: 'json', success: function (res) { var user = '<tr id="'+res.data.id+'">'; user += '<td>' + res.data.id + '</td>'; user += '<td>' + res.data.first_name + '</td>'; user += '<td>' + res.data.last_name + '</td>'; user += '<td>' + res.data.address + '</td>'; user += '<td><a data-id="' + res.data.id + '" class="btn btn-primary btnEdit">Edit</a> <a data-id="' + res.data.id + '" class="btn btn-danger btnDelete">Delete</a></td>'; user += '</tr>'; $('#userTable tbody').prepend(user); $('#addUser')[0].reset(); $('#addModal').modal('hide'); }, error: function (data) { } }); } }); //When click edit User $('body').on('click', '.btnEdit', function () { var user_id = $(this).attr('data-id'); $.ajax({ url: 'ajax_crud/edit/'+user_id, type: "GET", dataType: 'json', success: function (res) { $('#updateModal').modal('show'); $('#updateUser #hdnUserId').val(res.data.id); $('#updateUser #txtFirstName').val(res.data.first_name); $('#updateUser #txtLastName').val(res.data.last_name); $('#updateUser #txtAddress').val(res.data.address); }, error: function (data) { } }); }); // Update the User $("#updateUser").validate({ rules: { txtFirstName: "required", txtLastName: "required", txtAddress: "required" }, messages: { }, submitHandler: function(form) { var form_action = $("#updateUser").attr("action"); $.ajax({ data: $('#updateUser').serialize(), url: form_action, type: "POST", dataType: 'json', success: function (res) { var user = '<td>' + res.data.id + '</td>'; user += '<td>' + res.data.first_name + '</td>'; user += '<td>' + res.data.last_name + '</td>'; user += '<td>' + res.data.address + '</td>'; user += '<td><a data-id="' + res.data.id + '" class="btn btn-primary btnEdit">Edit</a> <a data-id="' + res.data.id + '" class="btn btn-danger btnDelete">Delete</a></td>'; $('#userTable tbody #'+ res.data.id).html(user); $('#updateUser')[0].reset(); $('#updateModal').modal('hide'); }, error: function (data) { } }); } }); //delete user $('body').on('click', '.btnDelete', function () { var user_id = $(this).attr('data-id'); $.get('ajax_crud/delete/'+user_id, function (data) { $('#userTable tbody #'+ user_id).remove(); }) }); }); </script> </div> </body> </html> |
We think would you like this article, so you can click on the “Show Demo” button and you can see this demo article.