Codeigniter CRUD Operation With Ajax Example – onlinecode

Codeigniter CRUD Operation With Ajax Example – onlinecode

In this post we will give you information about Codeigniter CRUD Operation With Ajax Example – onlinecode. Hear we will give you detail about Codeigniter CRUD Operation With Ajax Example – onlinecodeAnd how to use it also give you demo for it if it is necessary.

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 CodeigniterStep 2: Create a Database in tableStep 3: Connect to DatabaseStep 4: Create ControllerStep 5: Create a ModelStep 6: Create View File

Step 1: Download and install CodeigniterWe 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 tableIn 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 DatabaseGo 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
);

Step 4: Create ControllerIn 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));
		}
	}
}

?>

Step 5: Create a ModelIn 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;
        }
    }
}
?>

Step 6: Create View FileSo 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 >
    <div >
        <div >
            <h2>Codeigniter 3 Ajax CRUD Example</h2>
        </div>
        <div >
            <a  href="#" data-toggle="modal" data-target="#addModal">Add</a>
        </div>
    </div>

    <table  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']; ?>" >Edit</a>
			<a data-id="<?php echo $row['id']; ?>" >Delete</a>
			</td>
		</tr>
	<?php
}
?>
	</tbody>
</table>
		<!-- Add User Modal -->
		<div id="addModal"  role="dialog">
		  <div >
		 
			<!-- User Modal content-->
			<div >
			  <div >
				<button type="button"  data-dismiss="modal">&times;</button>
				<h4 >Add New User</h4>
			  </div>
			  <div >
				<form id="addUser" name="addUser" action="<?php echo base_url(); ?>ajax_crud/add" method="post">
					<div >
						<label for="txtFirstName">First Name:</label>
						<input type="text"  id="txtFirstName" placeholder="Enter First Name" name="txtFirstName">
					</div>
					<div >
						<label for="txtLastName">Last Name:</label>
						<input type="text"  id="txtLastName" placeholder="Enter Last Name" name="txtLastName">
					</div>
					<div >
						<label for="txtAddress">Address:</label>
						<pre  id="txtAddress" name="txtAddress" rows="10" placeholder="Enter Address"></pre>
					</div>
					<button type="submit" >Submit</button>
				</form>
			  </div>
			  <div >
				<button type="button"  data-dismiss="modal">Close</button>
			  </div>
			</div>
		  </div>
		</div>	
		<!-- Update User Modal -->
		<div id="updateModal"  role="dialog">
		  <div >
		 
			<!-- User Modal content-->
			<div >
			  <div >
				<button type="button"  data-dismiss="modal">&times;</button>
				<h4 >Update User</h4>
			  </div>
			  <div >
				<form id="updateUser" name="updateUser" action="<?php echo base_url(); ?>ajax_crud/update" method="post">
					<input type="hidden" name="hdnUserId" id="hdnUserId"/>
					<div >
						<label for="txtFirstName">First Name:</label>
						<input type="text"  id="txtFirstName" placeholder="Enter First Name" name="txtFirstName">
					</div>
					<div >
						<label for="txtLastName">Last Name:</label>
						<input type="text"  id="txtLastName" placeholder="Enter Last Name" name="txtLastName">
					</div>
					<div >
						<label for="txtAddress">Address:</label>
						<pre  id="txtAddress" name="txtAddress" rows="10" placeholder="Enter Address"></pre>
					</div>
					<button type="submit" >Submit</button>
				</form>
			  </div>
			  <div >
				<button type="button"  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 + '" >Edit</a>&nbsp;&nbsp;<a data-id="' + res.data.id + '" >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 + '" >Edit</a>&nbsp;&nbsp;<a data-id="' + res.data.id + '" >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

Please follow and like us:

Hope this code and post will helped you for implement Codeigniter CRUD Operation With Ajax Example – onlinecode. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

  +  2  =  10

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US