Ajax login system in codeigniter - Mostlikers

20 May, 2015

Ajax login system in codeigniter

In this tutorial, we are going to learn about how to create ajax login and set the user information to the session using CodeIgniter.Here I have used HMVC my model third-party libraries. For quick view have a look at the live demo.

Ajax login system in php codeigniter


Live demo               Download

Database

Create sample user table
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(100) NOT NULL,
  `password` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
)


Set database connection and add My model,Session,Database libraries in config autoload file. For new visitor go through this below link after add basic libraries file in your project.

- Add my model libraries in CodeIgniter.
- Basic steps of CodeIgniter.

Model

Create user_model in Application -> models folder.
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User_model extends MY_Model
{
    public function __construct()
    {
        parent::__construct();
        $this -> table = 'users';
        $this->primary_key='id';
        $this -> result_mode = 'object';
    }
    
}   

Controller

Create new controller or add below code in welcome controller. Application ->controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
        $this->load->model('user_model','users');
    }
    
    public function ajax_login()
    {
        if($user=$this->session->userdata('user_id')):      
            redirect(site_url('welcome/profile'));
        else :          
            $this->load->view('ajax_login');
        endif;          
    }
    
    public function user_login()
    {
        $login = array(
            'email'=> $this->input->post('email'),
            'password' => md5($this->input->post('password'))
        );
        if($this -> users->count_all_results($login)) :
            $user = $this -> users -> get($login);
                $this->session->set_userdata('user_id', $user->id);
                echo 1;
        else :
            echo 0;
        endif;          
    }

    public function profile()
    {
        if($user_id=$this->session->userdata('user_id')):
            $this->data['user_information']=$this->users->get($user_id);
            $this->load->view('profile',$this->data);               
        else :          
            redirect(site_url('welcome/ajax_login'));
        endif;      
    }

    public function ajax_logout()
    {
        $this->session->unset_userdata('user_id');
        redirect(site_url('welcome/ajax_login'));
    }

}


* Here I am using My model count_all_results functions  it will check rows value is there or not.

Views

For the view, I have designed pages bootstrap and validation I have used validation.min js file. Download all files use ajax_login.php and profile.php.

ajax_login.php
<form method="post" id="login_form">
  <div class="modal-body with-padding">                             
    <div class="form-group">
      <div class="row">
        <div class="col-sm-10">
          <label>Username *</label>
          <input type="text" id="username" name="username" class="required email">
        </div>
      </div>
    </div>
    <div class="form-group">
      <div class="row">
        <div class="col-sm-10">
          <label>Password *</label>
          <input type="password" id="password" name="password" class="required">
        </div>
      </div>
    </div> 
  </div>
  <div class="error" id="logerror"></div> 
  <div class="modal-footer">
    <input type="hidden" name="id" value="" id="id">
    <button type="submit" id="btn-login" class="btn btn-primary">Submit</button>              
  </div>
</form>

Ajax code
<script>  
  $(document).ready(function(){
    $('#login_form').validate(); // form validation  
    $(document).on('click','#btn-login',function(){
      var url = "<?php echo site_url('welcome/user_login');?>";       
        if($('#login_form').valid()){
          $.ajax({
            type: "POST",
            url: url,
            data: $("#login_form").serialize(), // serializes the form's elements.
            success: function(data)
             {
               if(data==1)              
               window.location.href = "<?php echo site_url('welcome/profile'); ?>";
               else
$('#logerror').html('The email or password you entered is incorrect.');
                     $('#logerror').addClass("error");
             }
          });
        }
       return false;
    });
  });
</script>

Thank you for visiting. if have any queries write comments below.


"Optimism is the faith that leads to achievement. Nothing can be done without hope and confidence. "
                                             
                                         - Helen Keller








Related Topics


16 comments:

  1. it is not working, when clicked on submit button nothing happens.

    ReplyDelete
  2. hiii i want to make a simple login page with ajax how can i do this

    ReplyDelete
    Replies
    1. http://www.mostlikers.com/2015/01/ajax-php-login-page-with-boostrap-design.html?m=1

      Delete
  3. hi, can you help me understand how the ajax_login() function is called.

    ReplyDelete
    Replies
    1. if($user=$this->session->userdata('user_id')):
      // checking session value if user already login redirect to profile page
      redirect(site_url('welcome/profile'));
      else :
      // checking session empty show login page
      $this->load->view('ajax_login');
      endif;

      Delete
  4. hi, thanks for the reply, but the mentioned one is the view, i was asking about (public function ajax_login())

    ReplyDelete
  5. Login file load function ex: http://localhost/yourfolder/welcome/ajax_login

    ReplyDelete
  6. hai thank for this tutorial
    i have error

    A PHP Error was encountered

    Severity: Error

    Message: Call to undefined method Mod_login::count_all_results()

    Filename: controllers/Login.php

    Line Number: 27

    Backtrace:

    ReplyDelete
    Replies
    1. Hi Rahmat,

      Here i am using my_model library. Please add that file.

      http://www.mostlikers.com/2015/04/codeigniter-my-model.html


      Delete
    2. it's put MY_Model.php in folder libraries?
      and in autoload.php i was
      $autoload['libraries'] = array('MY_Model');
      but i have new error

      A PHP Error was encountered

      Severity: Error

      Message: Class 'CI_Model' not found

      Filename: libraries/MY_Model.php

      Line Number: 11

      Backtrace:

      Delete
    3. I will update the code without my_model. Try this basic coding.

      http://www.mostlikers.com/2016/07/codeigniter-user-registration-and-login.html

      Delete
    4. thanks for your help.
      im new in CI.
      i will wait your update

      Delete
  7. Failed to load resource: the server responded with a status of 403 (Forbidden), can you help me ? tanks

    ReplyDelete