In this tutorial, We will inform you how to perform crud operation with ajax in CodeIgniter(Codeigniter CRUD Operation With Ajax Example).

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.

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.

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.

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.

$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
);

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

<?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));
		}
	}
}

?>

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

<?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;
        }
    }
}
?>

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

<!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">&times;</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">&times;</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>&nbsp;&nbsp;<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>&nbsp;&nbsp;<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.

Show Demo