In this article, you will learn how to create login functionality in CodeIgniter using Ajax from scratch.


MySQL users Table Structure

Use the following code to create a users table in MySQL 

-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Feb 21, 2021 at 04:15 AM
-- Server version: 10.4.17-MariaDB
-- PHP Version: 7.4.14

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `ci-tutorial`
--

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `id` int(11) UNSIGNED NOT NULL,
  `fullname` varchar(255) NOT NULL,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) DEFAULT NULL,
  `reg_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `fullname`, `username`, `password`, `reg_date`) VALUES
(1, 'Rathorji', 'test', 'test123', '2021-02-20 12:26:41');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


Configure CodeIgniter:

application/config/
┣ autoload.php
┣ config.php
┣ database.php

application/config/autoload.php

<?php

$autoload['libraries'] = array('database', 'session', 'form_validation');
$autoload['helper'] = array('url');


application/config/config.php -> to set the base url

<?php
$config['base_url'] = 'http://localhost/ci-tutorial/';


application/config/database.php

<?php

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'ci-tutorial',
	'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 View of login

We need one form of login so the user can enter a username and password.


application/views/login.php

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Login in CodeIgniter using Ajax from Scratch</title>
        <!--Include Jquery-->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <!--Include Bootstrap-->
        <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
        <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

        <style>

            body{
                background-image: url("<?php echo base_url(); ?>assets/images/body-bg.jpg");
                background-size: cover;
                background-repeat: no-repeat;
                background-attachment: fixed;
            }

            #login .container #login-row #login-column #login-box {
                margin-top: 60px;
                max-width: 600px;
                height: 320px;
                background-color: #f7f6f6;
            }

            #login .container #login-row #login-column #login-box #login-form {
                padding: 20px;
            }

            #response{
                color: red;
            }
        </style>
    </head>
    <body>
        <div class="login-wrap">
            <div id="login">
                <h3 class="text-center text-white pt-5">Login in CodeIgniter using Ajax</h3>
                <div class="container">
                    <div id="login-row" class="row justify-content-center align-items-center">
                        <div id="login-column" class="col-md-6">
                            <div id="login-box" class="col-md-12">
                                <!--HTML FORM-->
                                <div id="login-form" class="form">
                                    <h3 class="text-info">Login</h3>
                                    <p id="response"></p>
                                    <div class="form-group">
                                        <label for="username" class="text-info">Username:</label><br>
                                        <input type="text" name="username" id="username" class="form-control">
                                    </div>
                                    <div class="form-group">
                                        <label for="password" class="text-info">Password:</label><br>
                                        <input type="text" name="password" id="password" class="form-control">
                                    </div>
                                    <div class="form-group">
                                        <input type="submit" name="submit" class="btn btn-info btn-md" value="submit" onclick="submitform()">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>


        <script>

            function submitform() {


                var flag = 0;
                /*Checking the value of inputs*/
                var username = $('#username').val();
                var password = $('#password').val();
                /*Validating the values of inputs that it is neither null nor undefined.*/
                if (username == '' || username == undefined) {
                    $('#username').css('border', '1px solid red');
                    flag = 1;
                }
                if (password == '' || password == undefined) {
                    $('#password').css('border', '1px solid red');
                    flag = 1;
                }
                /*if there is no error, go to flag==0 condition*/
                if (flag == 0) {
                    /*Ajax call*/
                    $.ajax({
                        url: "<?php echo base_url('LoginController/getLogin') ?>",
                        method: 'POST',
                        data: "UserName=" + username + "&Password=" + password,
                        success: function (result) {
                            /*result is the response from LoginController.php file under getLogin.php function*/
                            if (result == 1) {
                                /*if response result is 1, it means it is successful.*/
                                $('#username').css('border', '1px solid green');
                                $('#password').css('border', '1px solid green');
                                setTimeout(function () {
                                    /*Redirect to login page after 1 sec*/
                                    window.location.href = '<?php echo base_url("LoginController/dashboard") ?>';
                                }, 1000)
                            } else if (result == 2) {
                                /*if response result is 2, it means, username is invalid.*/
                                $('#username').css('border', '1px solid red');
                                $('#response').html('Invalid Username');

                            } else if (result == 3) {
                                /*if response result is 3, it means, password is invalid.*/
                                $('#password').css('border', '1px solid red');
                                alert('Invalid Password');
                            } else if (result == 4 || result == 5) {
                                /*if response result is 4 or 5, it means, username & password are invalid.*/
                                $('#username').css('border', '1px solid red');
                                $('#password').css('border', '1px solid red');

                                $('#response').html('Invalid Username & Passowrd');
                            } else {

                                $('#response').html('Something went wrong');
                            }
                        }
                    });
                } else {
                    $('#response').html('Something went wrong');
                }
            }
        </script>
    </body>
</html>


Create controller to load view

now we need one controller file to load view and accept action form.


application/controllers/LoginController.php

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class LoginController extends CI_Controller {

    public function __construct() {
        parent::__construct();
        
        /* Load MLogin model*/
        $this->load->model('mlogin');
    }

    public function index() {
        /* Load the login screen, if the user is not log in */
        if (isset($_SESSION['login']['id'])) { 
            $this->load->view('dashboard');
        } else {
            /* if not, display the login window */
            $this->load->view('login');
        }
    }

    public function dashboard() {
        /* Load the dashboard screen, if the user is already log in */
        if (isset($_SESSION['login']['id'])) {
            $this->load->view('dashboard');
        } else {
            $this->load->view('login');
        }
    }

    function getLogin() {
        /* Data that we receive from ajax */
        $username = $this->input->post('UserName');
        $Password = $this->input->post('Password');
        if (!isset($username) || $username == '' || $username == 'undefined') {
            /* If Username that we recieved is invalid, go here, and return 2 as output */
            echo 2;
            exit();
        }
        if (!isset($Password) || $Password == '' || $Password == 'undefined') {
            /* If Password that we recieved is invalid, go here, and return 3 as output */
            echo 3;
            exit();
        }
        $this->form_validation->set_rules('UserName', 'UserName', 'required');
        $this->form_validation->set_rules('Password', 'Password', 'required');
        if ($this->form_validation->run() == FALSE) {
            /* If Both Username &  Password that we recieved is invalid, go here, and return 4 as output */
            echo 4;
            exit();
        } else {
            /* Create object of model MLogin.php file under models folder */
            $Login = new MLogin();
            /* validate($username, $Password) is the function in Mlogin.php */
            $result = $Login->validate($username, $Password);
            if (count($result) == 1) {
                /* If everything is fine, then go here, and return 1 as output and set session */
                $data = array(
                    'id' => $result[0]->id,
                    'username' => $result[0]->username
                );
                $this->session->set_userdata('login', $data);
                echo 1;
            } else {
                /* If Both Username &  Password that we recieved is invalid, go here, and return 5 as output */
                echo 5;
            }
        }
    }

}


Create model to execute MySQL Query

lets create model to write query and check the entered username and password to database table if its match then we can login to user.


application/models/Mlogin.php

<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class MLogin extends CI_Model {

    public $Modal;

    public function __construct() {
        parent::__construct();
    }

    /* function to use fetch the data from users table */

    function validate($user, $pass) {
        $this->db->select('*');
        $this->db->from('users');
        $this->db->where('password', $pass);
        $this->db->where('username', $user);
        $query = $this->db->get();
        $res = $query->result();
        return $res;
    }

}


Remove index.php from URL

using the following code in your .htaccess file to remove index.php from url


#remove index.php
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]


Run the code

http://localhost/ci-tutorial/LoginController





Are you facing problems in understanding this article?
You can watch the video. Watch it now