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. class Login extends CI_Controller {
  4. function __construct()
  5. {
  6. parent::__construct();
  7. $this->load->helper('url');//you can autoload this functions by configuring autoload.php in config directory
  8. $this->load->library ( 'session' );
  9. $this->load->model('data_model');
  10. }
  11. public function index(){
  12. $this->load->view('login');
  13. }
  14. public function check_login(){
  15. $data['username']=htmlspecialchars($_POST['name']);
  16. $data['password']=htmlspecialchars($_POST['pwd']);
  17. $res=$this->data_model->islogin($data);
  18. if($res){
  19. $this->session->set_userdata('id',$data['username']);
  20. echo base_url()."dashboard/";
  21. }
  22. else{
  23. echo 0;
  24. }
  25. }
  26. public function logout(){
  27. $this->session->sess_destroy();
  28. header('location:'.base_url()."login/".$this->index());
  29. }
  30. }
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. <head>
  4. <meta charset="utf-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1">
  7. <title>Myapp</title>
  8. <!-- CSS -->
  9. <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
  10. <link rel="stylesheet" href="<?php echo CSS_PATH; ?>w3.css">
  11. <link rel="stylesheet" href="<?php echo CSS_PATH; ?>bootstrap.min.css">
  12. <style>
  13. body,h1 {font-family: "Raleway", sans-serif}
  14. body, html {height: 100%}
  15. .bgimg {
  16. background-image: url('<?php echo IMAGE_PATH; ?>/1.jpg');
  17. min-height: 100%;
  18. background-position: center;
  19. background-size: cover;
  20. }
  21. </style>
  22. </head>
  23. <body>
  24. <div class="bgimg w3-display-container w3-animate-opacity w3-text-white">
  25. <div class="w3-display-topleft w3-padding-large w3-xlarge">
  26. </div>
  27. <div class="container">
  28. <div class="w3-display-middle w3-animate-opacity">
  29. <h2 class="w3-jumbo ">Myapp Login</h2>
  30. <hr class="w3-border-grey" style="margin:auto;width:40%">
  31. <br><br>
  32. <form class="w3-container" method="post">
  33. <label>User Name</label>
  34. <input class="w3-input w3-border w3-light-grey" type="text" id="name" placeholder="Username">
  35. <label>Password</label>
  36. <input class="w3-input w3-border w3-light-grey" type="password" id="pwd" placeholder="Password">
  37. <br>
  38. <input class="w3-btn w3-white w3-border w3-round-large" type="submit" value="Login" id="submit" >
  39. <div id='err_msg' style='display: none'>
  40. <div id='content_result'>
  41. <div id='err_show' class="w3-text-red">
  42. <div id='msg'> </div></label>
  43. </div></div></div>
  44. </form>
  45. </div>
  46. <div class="w3-display-bottomleft w3-padding-large">
  47. Powered by <a href="http://simelabs.com/" target="_blank">simelabs</a>
  48. </div>
  49. </div>
  50. </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. // Ajax post
  4. $(document).ready(function(){
  5. $("#submit").click(function(){
  6. var user_name = $("#name").val();
  7. var password = $("#pwd").val();
  8. // Returns error message when submitted without req fields.
  9. if(user_name==''||password=='')
  10. {
  11. jQuery("div#err_msg").show();
  12. jQuery("div#msg").html("All fields are required");
  13. }
  14. else
  15. {
  16. // AJAX Code To Submit Form.
  17. $.ajax({
  18. type: "POST",
  19. url: "<?php echo base_url(); ?>" + "login/check_login",
  20. data: {name: user_name, pwd: password},
  21. cache: false,
  22. success: function(result){
  23. if(result!=0){
  24. // On success redirect.
  25. window.location.replace(result);
  26. }
  27. else
  28. jQuery("div#err_msg").show();
  29. jQuery("div#msg").html("Login Failed");
  30. }
  31. });
  32. }
  33. return false;
  34. });
  35. });
  36. </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. public function islogin($data){
  9. $query=$this->db->get_where('tbluser',array('uname'=>$data['username'],'upwd'=>$data['password']));
  10. return $query->num_rows();
  11. }
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