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.
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.
* Here I am using My model count_all_results functions it will check rows value is there or not.
- 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
Thanks so much!
ReplyDeleteit is not working, when clicked on submit button nothing happens.
ReplyDeleteShare your error msg
Deletehiii i want to make a simple login page with ajax how can i do this
ReplyDeletehttp://www.mostlikers.com/2015/01/ajax-php-login-page-with-boostrap-design.html?m=1
Deletehi, can you help me understand how the ajax_login() function is called.
ReplyDeleteif($user=$this->session->userdata('user_id')):
Delete// 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;
hi, thanks for the reply, but the mentioned one is the view, i was asking about (public function ajax_login())
ReplyDeleteLogin file load function ex: http://localhost/yourfolder/welcome/ajax_login
ReplyDeleteThanks. Now I understood.
ReplyDeletehai thank for this tutorial
ReplyDeletei 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:
Hi Rahmat,
DeleteHere i am using my_model library. Please add that file.
http://www.mostlikers.com/2015/04/codeigniter-my-model.html
it's put MY_Model.php in folder libraries?
Deleteand 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:
I will update the code without my_model. Try this basic coding.
Deletehttp://www.mostlikers.com/2016/07/codeigniter-user-registration-and-login.html
thanks for your help.
Deleteim new in CI.
i will wait your update
Failed to load resource: the server responded with a status of 403 (Forbidden), can you help me ? tanks
ReplyDeleteFatal error: Call to undefined method Model::count_all_results() in D:\xampp\htdocs\relimail\application\controllers\Admin_login.php on line 55
ReplyDeleteA PHP Error was encountered
Severity: Error
Message: Call to undefined method Model::count_all_results()
Filename: controllers/Admin_login.php
Line Number: 55
Backtrace:
This comment has been removed by a blog administrator.
ReplyDelete