Codeigniter Login With AJAX

In this blog I will show you how to create a login page in Codeigniter using AJAX.
 
First, we need to create a database for the project. I created a 'testdb' database and a table named 'tbluser' in it. SQL query for the table is as below:
  1. CREATE TABLE `tbluser` (  
  2.   `id` int(11) NOT NULL,  
  3.   `uname` varchar(100) NOT NULL,  
  4.   `upwd` varchar(100) NOT NULL,  
  5.   `urole` varchar(100) NOT NULL,  
  6.   `intusertype` int(11) NOT NULL,  
  7.   `struseremail` varchar(50) DEFAULT NULL  
  8. ) ENGINE=InnoDB DEFAULT CHARSET=latin1;   
Now, we have to set up a few config files in codeigniter to get started.
 
Set the database connection settings in config> database.php file,
  1. 'hostname' => 'localhost',   
  2. 'username' => 'root',   
  3. 'password' => '',  
  4. 'database' => 'testdb',   
Add the default paths in config>config.php
  1. $config['base_url'] = 'http://localhost/codeig/';  
  2. define ( "DIR_ROOT"$_SERVER ["DOCUMENT_ROOT"] . '/app/' );  
  3. define ( "URI_ROOT"$config ['base_url'] );  
  4. define ( "CSS_PATH"$config ['base_url'] . "css/" );  
  5. define ( "IMAGE_PATH"$config ['base_url'] . "img/" );  
  6. define ( "JS_PATH"$config ['base_url'] . "js/" );  
Set the default route; i.e.; to which controller should the app point when the url is called. You can change this at config>routes.php
  1. $route['default_controller'] = 'login';  
  2. $route['404_override'] = '';  
  3. $route['translate_uri_dashes'] = FALSE;  

Controller

Inside controllers folder create a new controller named Login.php. The code for it is as below..
  1. <?php  
  2. if ( ! defined('BASEPATH')) exit('No direct script access allowed');  
  3.   
  4. class Login extends CI_Controller {  
  5. function __construct()  
  6. {  
  7.     parent::__construct();  
  8.     $this->load->helper('url');//you can autoload this functions by configuring autoload.php in config directory  
  9.     $this->load->library ( 'session' );  
  10.     $this->load->model('data_model');  
  11. }  
  12. public function index(){  
  13.     $this->load->view('login');  
  14. }  
  15. public function check_login(){  
  16.      
  17.     $data['username']=htmlspecialchars($_POST['name']);  
  18.     $data['password']=htmlspecialchars($_POST['pwd']);  
  19.     $res=$this->data_model->islogin($data);  
  20.     if($res){     
  21.         $this->session->set_userdata('id',$data['username']);   
  22.       echo base_url()."dashboard/";  
  23.     }  
  24.     else{  
  25.        echo 0;  
  26.     }   
  27. }  
  28. public function logout(){  
  29.     $this->session->sess_destroy();  
  30.     header('location:'.base_url()."login/".$this->index());  
  31.       
  32. }  
  33. }  
As you can see in its index method we are redirecting to our first view login.

View

Now, create a new file under view folder called login.php. I have used w3.css for the design part. The form contains two input boxes and a button for submit.

Also a div tag is used to show error messages.
  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3.   
  4.     <head>  
  5.   
  6.         <meta charset="utf-8">  
  7.         <meta http-equiv="X-UA-Compatible" content="IE=edge">  
  8.         <meta name="viewport" content="width=device-width, initial-scale=1">  
  9.         <title>Myapp</title>  
  10.   
  11.         <!-- CSS -->  
  12.        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">  
  13.         <link rel="stylesheet" href="<?php echo CSS_PATH; ?>w3.css">  
  14.         <link rel="stylesheet" href="<?php echo CSS_PATH; ?>bootstrap.min.css">  
  15.        <style>  
  16.         body,h1 {font-family: "Raleway", sans-serif}  
  17.         body, html {height: 100%}  
  18.         .bgimg {  
  19.             background-image: url('<?php echo IMAGE_PATH; ?>/1.jpg');  
  20.             min-height: 100%;  
  21.             background-position: center;  
  22.             background-size: cover;  
  23.         }  
  24.         </style>  
  25.           
  26.     </head>  
  27.   
  28.     <body>  
  29. <div class="bgimg w3-display-container w3-animate-opacity w3-text-white">  
  30.   <div class="w3-display-topleft w3-padding-large w3-xlarge">  
  31.       
  32.   </div>  
  33.          
  34.         <div class="container">  
  35.           <div class="w3-display-middle w3-animate-opacity">  
  36.             <h2 class="w3-jumbo ">Myapp Login</h2>  
  37.             <hr class="w3-border-grey" style="margin:auto;width:40%">  
  38.             <br><br>  
  39.             <form class="w3-container" method="post">  
  40.               <label>User Name</label>  
  41.               <input class="w3-input w3-border w3-light-grey" type="text" id="name" placeholder="Username">  
  42.   
  43.               <label>Password</label>  
  44.               <input class="w3-input w3-border w3-light-grey" type="password" id="pwd" placeholder="Password">  
  45.               <br>  
  46.               <input class="w3-btn w3-white w3-border w3-round-large" type="submit" value="Login" id="submit" >  
  47.               <div id='err_msg' style='display: none'>  
  48.                 <div id='content_result'>  
  49.                 <div id='err_show' class="w3-text-red">  
  50.                 <div id='msg'> </div></label>  
  51.                 </div></div></div>  
  52.             </form>  
  53.           </div>  
  54.           <div class="w3-display-bottomleft w3-padding-large">  
  55.             Powered by <a href="http://simelabs.com/" target="_blank">simelabs</a>  
  56.           </div>  
  57.         </div>  
  58. </div>  
AJAX code posts the  submitted value to the server..
  1. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
  2.         <script type="text/javascript">  
  3.   
  4.         // Ajax post  
  5.         $(document).ready(function(){  
  6.         $("#submit").click(function(){  
  7.         var user_name = $("#name").val();  
  8.         var password = $("#pwd").val();  
  9.         // Returns error message when submitted without req fields.  
  10.         if(user_name==''||password=='')  
  11.         {  
  12.         jQuery("div#err_msg").show();  
  13.         jQuery("div#msg").html("All fields are required");  
  14.         }  
  15.         else  
  16.         {  
  17.         // AJAX Code To Submit Form.  
  18.         $.ajax({  
  19.         type: "POST",  
  20.         url:  "<?php echo base_url(); ?>" + "login/check_login",  
  21.         data: {name: user_name, pwd: password},  
  22.         cache: false,  
  23.         success: function(result){  
  24.             if(result!=0){  
  25.                 // On success redirect.  
  26.             window.location.replace(result);  
  27.             }  
  28.             else  
  29.                 jQuery("div#err_msg").show();  
  30.                 jQuery("div#msg").html("Login Failed");  
  31.         }  
  32.         });  
  33.         }  
  34.         return false;  
  35.         });  
  36.         });  
  37.         </script>   

Model

Create data_model.php under folder models.
  1. <?php  
  2. class data_model extends CI_Model {  
  3. function __construct()  
  4. {  
  5.     parent::__construct();  
  6.     $this->load->database();  
  7. }  
  8.   
  9. public function islogin($data){  
  10.     $query=$this->db->get_where('tbluser',array('uname'=>$data['username'],'upwd'=>$data['password']));  
  11.     return $query->num_rows();  
  12. }  
That's it -- run the code in the browser. And you have created a new controller dashboard.php and views so as to redirect it on successful login.
 
G
M
T
 
Text-to-speech function is limited to 200 characters
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now