Skip to main content

Creating a CodeIniter App using jQuery Ajax

Screenshot
Body

This tutorial tackles how to create an Ajax Login in CodeIgniter. We used jQuery to handle our ajax request to our controller. jQuery is a javascript library that makes you handle javascript better. CodeIgniter is a lightweight PHP framework that uses the MVC(Model-View-Controller) architecture.

Installing CodeIgniter

If you don't have CodeIgniter installed yet, you can use this link to download the latest version of CodeIgniter which is 3.1.7 that I've used in this tutorial.Then download the jQuery library, click here to download. I have used also Bootstrap for the design

After downloading, extract the file in the folder of your server. Since I'm using XAMPP as my localhost server, I've put the folder in htdocs folder of my XAMPP.

Then, you can test whether you have successfully installed Codeigniter by typing your app name in your browser. In my case, I named my app as codeigniter_login_ajax so I'm using the below code.

  1. localhost/codeigniter_login_ajax/
codeigiter successful install

Creating our Database

First, we are going to create our database and insert sample data for this tutorial.

  1. Open your PHPMyAdmin.
  2. Create a new database named codeigniter.
  3. Click the database that we created, click the SQL tab then paste the below code or import the included .sql file in the downloadable of this source code located in the db folder.
  1. CREATE TABLE `users` (
  2. `email` varchar(40) NOT NULL,
  3. `password` varchar(40) NOT NULL,
  4. `fname` varchar(100) NOT NULL,
  1. INSERT INTO `users` (`id`, `email`, `password`, `fname`) VALUES
  2. (1, '[email protected]', 'nurhodelta', 'Neovic Devierte'),
  3. (2, '[email protected]', 'cepe', 'Gemalyn Cepe');
You can then use the ff. login credentials:

Email: [email protected]
Password: nurhodelta

Email: [email protected]
Password: cepe

Connecting our App into our Database

Next, we're going to connect our Codeigniter application to the database that we created earlier.

  1. In your codeigniter app folder, open database.php located in application/config folder.
  2. Update database.php with your credential the same as what I did in the image below.

The database is where we define the database that we created earlier.

database configuration codeigniter

Configuring our Base URL

Next, we configure our base_url to tell Codeigniter that this is the URL of our site/application. We're gonna be using this a lot that's why we need to configure this.

  1. In your codeigniter app folder, open config.php located in application/config folder.
  2. Find and edit the ff line:
    1. $config['base_url'] = 'http://localhost/codeigniter_login_ajax/';

The codeigniter_login_ajax is the name of your app folder.

Creating our Model

Next, we create the model for our app. Take note that the first letter of your model name should be in a CAPITAL letter and the name of the model should be the same as the file name to avoid confusion.

Create a file named Users_model.php in application/models folder of our app and put the ff codes.

  1. <?php
  2. class Users_model extends CI_Model {
  3. function __construct(){
  4. parent::__construct();
  5. $this->load->database();
  6. }
  7.  
  8. public function login($email, $password){
  9. $query = $this->db->get_where('users', array('email'=>$email, 'password'=>$password));
  10. return $query->row_array();
  11. }
  12.  
  13. }
  14. ?>

Creating our Controller

The next step is to create our controller. Controllers follow the same naming convention as models.

Create a file named User.php in application/controllers folder of our app and put the ff codes.

  1. <?php
  2. defined('BASEPATH') OR exit('No direct script access allowed');
  3.  
  4. class User extends CI_Controller {
  5.  
  6. function __construct(){
  7. parent::__construct();
  8. $this->load->helper('url');
  9. $this->load->model('users_model');
  10. }
  11.  
  12. public function index(){
  13. //load session library
  14. $this->load->library('session');
  15.  
  16. //restrict users to go back to login if session has been set
  17. if($this->session->userdata('user')){
  18. redirect('user/home');
  19. }
  20. else{
  21. $this->load->view('login_page');
  22. }
  23. }
  24.  
  25. public function login(){
  26. //load session library
  27. $this->load->library('session');
  28.  
  29. $output = array('error' => false);
  30.  
  31. $email = $_POST['email'];
  32. $password = $_POST['password'];
  33.  
  34. $data = $this->users_model->login($email, $password);
  35.  
  36. if($data){
  37. $this->session->set_userdata('user', $data);
  38. $output['message'] = 'Logging in. Please wait...';
  39. }
  40. else{
  41. $output['error'] = true;
  42. $output['message'] = 'Login Invalid. User not found';
  43. }
  44.  
  45. echo json_encode($output);
  46. }
  47.  
  48. public function home(){
  49. //load session library
  50. $this->load->library('session');
  51.  
  52. //restrict users to go to home if not logged in
  53. if($this->session->userdata('user')){
  54. $this->load->view('home');
  55. }
  56. else{
  57. redirect('/');
  58. }
  59.  
  60. }
  61.  
  62. public function logout(){
  63. //load session library
  64. $this->load->library('session');
  65. $this->session->unset_userdata('user');
  66. redirect('/');
  67. }
  68.  
  69. }

Defining our Default Controller

Next, we are going to set our default controller so that if no controller is defined, this default controller will be used.

Open routes.php located in application/config folder and set the default route to our user controller.

  1. $route['default_controller'] = 'user';

Creating our Views

Lastly, we create the views of our app.

Create the ff files inside the application/views folder.

login_page.php
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>CodeIgniter Ajax Login using jQuery</title>
  6. <link rel="stylesheet" href="<?php echo base_url(); ?>bootstrap/css/bootstrap.min.css">
  7. <script src="<?php echo base_url(); ?>jquery/jquery.min.js"></script>
  8. <script src="<?php echo base_url(); ?>bootstrap/js/bootstrap.min.js"></script>
  9. </head>
  10. <body>
  11. <div class="container">
  12. <h1 class="page-header text-center">CodeIgniter Ajax Login using jQuery</h1>
  13. <div class="row">
  14. <div class="col-sm-4 col-sm-offset-4">
  15. <div class="login-panel panel panel-primary">
  16. <div class="panel-heading">
  17. <h3 class="panel-title"><span class="glyphicon glyphicon-lock"></span> Login
  18. </h3>
  19. </div>
  20. <div class="panel-body">
  21. <form id="logForm">
  22. <fieldset>
  23. <div class="form-group">
  24. <input class="form-control" placeholder="Email" type="text" name="email">
  25. </div>
  26. <div class="form-group">
  27. <input class="form-control" placeholder="Password" type="password" name="password">
  28. </div>
  29. <button type="submit" class="btn btn-lg btn-primary btn-block"><span id="logText"></span></button>
  30. </fieldset>
  31. </form>
  32. </div>
  33. </div>
  34. <div id="responseDiv" class="alert text-center" style="margin-top:20px; display:none;">
  35. <button type="button" class="close" id="clearMsg"><span aria-hidden="true">&times;</span></button>
  36. <span id="message"></span>
  37. </div>
  38. </div>
  39. </div>
  40. </div>
  41. <script type="text/javascript">
  42. $(document).ready(function(){
  43. $('#logText').html('Login');
  44. $('#logForm').submit(function(e){
  45. e.preventDefault();
  46. $('#logText').html('Checking...');
  47. var url = '<?php echo base_url(); ?>';
  48. var user = $('#logForm').serialize();
  49. var login = function(){
  50. $.ajax({
  51. type: 'POST',
  52. url: url + 'index.php/user/login',
  53. dataType: 'json',
  54. data: user,
  55. success:function(response){
  56. $('#message').html(response.message);
  57. $('#logText').html('Login');
  58. if(response.error){
  59. $('#responseDiv').removeClass('alert-success').addClass('alert-danger').show();
  60. }
  61. else{
  62. $('#responseDiv').removeClass('alert-danger').addClass('alert-success').show();
  63. $('#logForm')[0].reset();
  64. setTimeout(function(){
  65. location.reload();
  66. }, 3000);
  67. }
  68. }
  69. });
  70. };
  71. setTimeout(login, 3000);
  72. });
  73.  
  74. $(document).on('click', '#clearMsg', function(){
  75. $('#responseDiv').hide();
  76. });
  77. });
  78. </script>
  79. </body>
  80. </html>
home.php
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>CodeIgniter Ajax Login using jQuery</title>
  6. <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>bootstrap/css/bootstrap.min.css">
  7. </head>
  8. <body>
  9. <div class="container">
  10. <h1 class="page-header text-center">CodeIgniter Ajax Login using jQuery</h1>
  11. <div class="row">
  12. <div class="col-md-4 col-md-offset-4">
  13. <?php
  14. $user = $this->session->userdata('user');
  15. extract($user);
  16. ?>
  17. <h2>Welcome to Homepage </h2>
  18. <h4>User Info:</h4>
  19. <p>Fullname: <?php echo $fname; ?></p>
  20. <p>Email: <?php echo $email; ?></p>
  21. <p>Password: <?php echo $password; ?></p>
  22. <a href="<?php echo base_url(); ?>index.php/user/logout" class="btn btn-danger">Logout</a>
  23. </div>
  24. </div>
  25. </div>
  26. </body>
  27. </html>
DEMO

That ends this tutorial. You can download the working source code that I have created and used in this tutorial. The download button is located below.

Happy Coding :)

Comments

I had a login problem with my Gmail account saying something went wrong. I opened my account in my laptop having windows OS7, Now when I wanted to log in but this error is shown. this can resolve by contacting the BT Mail Support If you login or sign in a problem with your Gmail account contact to BT maul support for quick help and solution

Add new comment