Creating a CRUD Web App using CodeIgniter, jQuery, and Ajax Tutorial
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
- Open a web browser and browse the PHPMyAdmin i.e.
http://localhost/phpmyadmin
- Create a new database naming
codeigniter
- Copy the
SQL Script
below andpaste
it in the SQL Tab of your PHPMyAdmin and click the Go Button.
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.
- $config['base_url'] = 'http://localhost/sourcecodester/codeigniter_crud_ajax';
Configuring the Database Connection
Open the database.php
file located inside the application/config
directory and follow configuration below.
- 'dsn' => '',
- 'hostname' => 'localhost',
- 'username' => 'root',
- 'password' => '',
- 'database' => 'codeigniter',
- 'dbdriver' => 'mysqli',
- 'dbprefix' => '',
- 'pconnect' => TRUE,
- 'db_debug' => (ENVIRONMENT !== 'production'),
- 'cache_on' => FALSE,
- 'cachedir' => '',
- 'char_set' => 'utf8',
- 'dbcollat' => 'utf8_general_ci',
- 'swap_pre' => '',
- 'encrypt' => FALSE,
- 'compress' => FALSE,
- 'stricton' => FALSE,
- 'save_queries' => TRUE
- );
Creating the .htaccess file
This file will remove the .htaccess
in the URL.
- <IfModule mod_rewrite.c>
- RewriteEngine On
- RewriteCond %{REQUEST_FILENAME} !-f
- RewriteCond %{REQUEST_FILENAME} !-d
- RewriteRule ^(.*)$ index.php/$1 [L]
- </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
.
- <?php
- class User extends CI_Controller {
- function __construct(){
- parent::__construct();
- $this->load->helper('url');
- $this->load->model('users_model');
- //include modal.php in views
- $this->inc['modal'] = $this->load->view('modal', '', true);
- }
- public function index(){
- $this->load->view('show', $this->inc);
- }
- public function show(){
- $data = $this->users_model->show();
- foreach($data as $row){
- ?>
- <tr>
- <td><?php echo $row->id; ?></td>
- <td><?php echo $row->email; ?></td>
- <td><?php echo $row->password; ?></td>
- <td><?php echo $row->fname; ?></td>
- <td>
- <button class="btn btn-warning edit" data-id="<?php echo $row->id; ?>"><span class="glyphicon glyphicon-edit"></span> Edit</button> ||
- <button class="btn btn-danger delete" data-id="<?php echo $row->id; ?>"><span class="glyphicon glyphicon-trash"></span> Delete</button>
- </td>
- </tr>
- <?php
- }
- }
- public function insert(){
- $user['email'] = $_POST['email'];
- $user['password'] = $_POST['password'];
- $user['fname'] = $_POST['fname'];
- $query = $this->users_model->insert($user);
- }
- public function getuser(){
- $id = $_POST['id'];
- $data = $this->users_model->getuser($id);
- }
- public function update(){
- $id = $_POST['id'];
- $user['email'] = $_POST['email'];
- $user['password'] = $_POST['password'];
- $user['fname'] = $_POST['fname'];
- $query = $this->users_model->updateuser($user, $id);
- }
- public function delete(){
- $id = $_POST['id'];
- $query = $this->users_model->delete($id);
- }
- }
Chnage the default application's controller to user. To do this, kindly open the routes.php
file inside the application/config
directory.
- $route['default_controller'] = 'user';
- $route['404_override'] = '';
- $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.
- <?php
- class Users_model extends CI_Model {
- function __construct(){
- parent::__construct();
- $this->load->database();
- }
- public function show(){
- $query = $this->db->get('users');
- return $query->result();
- }
- public function insert($user){
- return $this->db->insert('users', $user);
- }
- public function getuser($id){
- return $query->row_array();
- }
- public function updateuser($user, $id){
- $this->db->where('users.id', $id);
- return $this->db->update('users', $user);
- }
- public function delete($id){
- $this->db->where('users.id', $id);
- return $this->db->delete('users');
- }
- }
- ?>
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
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>CodeIgniter Ajax CRUD using jQuery</title>
- <link rel="stylesheet" href="<?php echo base_url(); ?>bootstrap/css/bootstrap.min.css">
- <script src="<?php echo base_url(); ?>jquery/jquery.min.js"></script>
- <script src="<?php echo base_url(); ?>bootstrap/js/bootstrap.min.js"></script>
- </head>
- <body>
- <div class="container">
- <h1 class="page-header text-center">CodeIgniter Ajax CRUD using jQuery</h1>
- <div class="row">
- <div class="col-sm-8 col-sm-offset-2">
- <button class="btn btn-primary" id="add"><span class="glyphicon glyphicon-plus"></span> Add New</button>
- <table class="table table-bordered table-striped" style="margin-top:20px;">
- <thead>
- <tr>
- <th>ID</th>
- <th>Email</th>
- <th>Password</th>
- <th>FullName</th>
- <th>Action</th>
- </tr>
- </thead>
- <tbody id="tbody">
- </tbody>
- </table>
- </div>
- </div>
- <?php echo $modal; ?>
- <script type="text/javascript">
- $(document).ready(function(){
- //create a global variable for our base url
- var url = '<?php echo base_url(); ?>';
- //fetch table data
- showTable();
- //show add modal
- $('#add').click(function(){
- $('#addnew').modal('show');
- $('#addForm')[0].reset();
- });
- //submit add form
- $('#addForm').submit(function(e){
- e.preventDefault();
- var user = $('#addForm').serialize();
- $.ajax({
- type: 'POST',
- url: url + 'user/insert',
- data: user,
- success:function(){
- $('#addnew').modal('hide');
- showTable();
- }
- });
- });
- //show edit modal
- $(document).on('click', '.edit', function(){
- var id = $(this).data('id');
- $.ajax({
- type: 'POST',
- url: url + 'user/getuser',
- dataType: 'json',
- data: {id: id},
- success:function(response){
- console.log(response);
- $('#email').val(response.email);
- $('#password').val(response.password);
- $('#fname').val(response.fname);
- $('#userid').val(response.id);
- $('#editmodal').modal('show');
- }
- });
- });
- //update selected user
- $('#editForm').submit(function(e){
- e.preventDefault();
- var user = $('#editForm').serialize();
- $.ajax({
- type: 'POST',
- url: url + 'user/update',
- data: user,
- success:function(){
- $('#editmodal').modal('hide');
- showTable();
- }
- });
- });
- //show delete modal
- $(document).on('click', '.delete', function(){
- var id = $(this).data('id');
- $.ajax({
- type: 'POST',
- url: url + 'user/getuser',
- dataType: 'json',
- data: {id: id},
- success:function(response){
- console.log(response);
- $('#delfname').html(response.fname);
- $('#delid').val(response.id);
- $('#delmodal').modal('show');
- }
- });
- });
- $('#delid').click(function(){
- var id = $(this).val();
- $.ajax({
- type: 'POST',
- url: url + 'user/delete',
- data: {id: id},
- success:function(){
- $('#delmodal').modal('hide');
- showTable();
- }
- });
- });
- });
- function showTable(){
- var url = '<?php echo base_url(); ?>';
- $.ajax({
- type: 'POST',
- url: url + 'user/show',
- success:function(response){
- $('#tbody').html(response);
- }
- });
- }
- </script>
- </div>
- </body>
- </html>
modal.php
- <!-- Add New -->
- <div class="modal fade" id="addnew" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
- <div class="modal-dialog">
- <div class="modal-content">
- <div class="modal-header">
- <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
- <center><h4 class="modal-title" id="myModalLabel">Add New Member</h4></center>
- </div>
- <div class="modal-body">
- <div class="container-fluid">
- <form id="addForm">
- <div class="row">
- <div class="col-md-3">
- <label class="control-label" style="position:relative; top:7px;">Email:</label>
- </div>
- <div class="col-md-9">
- <input type="email" class="form-control" name="email" required>
- </div>
- </div>
- <div style="height:10px;"></div>
- <div class="row">
- <div class="col-md-3">
- <label class="control-label" style="position:relative; top:7px;">Password:</label>
- </div>
- <div class="col-md-9">
- <input type="password" class="form-control" name="password" required>
- </div>
- </div>
- <div style="height:10px;"></div>
- <div class="row">
- <div class="col-md-3">
- <label class="control-label" style="position:relative; top:7px;">Full Name:</label>
- </div>
- <div class="col-md-9">
- <input type="text" class="form-control" name="fname" required>
- </div>
- </div>
- </div>
- </div>
- <div class="modal-footer">
- <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
- <button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Save</a>
- </form>
- </div>
- </div>
- </div>
- </div>
- <!-- Edit -->
- <div class="modal fade" id="editmodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
- <div class="modal-dialog">
- <div class="modal-content">
- <div class="modal-header">
- <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
- <center><h4 class="modal-title" id="myModalLabel">Edit Member</h4></center>
- </div>
- <div class="modal-body">
- <div class="container-fluid">
- <form id="editForm">
- <div class="row">
- <div class="col-md-3">
- <label class="control-label" style="position:relative; top:7px;">Email:</label>
- </div>
- <div class="col-md-9">
- <input type="text" class="form-control" name="email" id="email">
- </div>
- </div>
- <div style="height:10px;"></div>
- <div class="row">
- <div class="col-md-3">
- <label class="control-label" style="position:relative; top:7px;">Password:</label>
- </div>
- <div class="col-md-9">
- <input type="text" class="form-control" name="password" id="password">
- </div>
- </div>
- <div style="height:10px;"></div>
- <div class="row">
- <div class="col-md-3">
- <label class="control-label" style="position:relative; top:7px;">Full Name:</label>
- </div>
- <div class="col-md-9">
- <input type="text" class="form-control" name="fname" id="fname">
- </div>
- </div>
- <input type="hidden" name="id" id="userid">
- </div>
- </div>
- <div class="modal-footer">
- <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
- <button type="submit" class="btn btn-warning"><span class="glyphicon glyphicon-check"></span> Update</a>
- </form>
- </div>
- </div>
- </div>
- </div>
- <!-- Delete -->
- <div class="modal fade" id="delmodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
- <div class="modal-dialog">
- <div class="modal-content">
- <div class="modal-header">
- <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
- <center><h4 class="modal-title" id="myModalLabel">Delete Member</h4></center>
- </div>
- <div class="modal-body">
- <h4 class="text-center">Are you sure you want to delete</h4>
- <h2 id="delfname" class="text-center"></h2>
- </div>
- <div class="modal-footer">
- <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
- <button type="button" id="delid" class="btn btn-danger"><span class="glyphicon glyphicon-trash"></span> Yes</button>
- </div>
- </div>
- </div>
- </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
- Add new comment
- 7480 views