• We just launched and are currently in beta. Join us as we build and grow the community.

Creating a CodeIniter App using jQuery Ajax

ashdash

Threat Landscape Analyst
Divine
A Rep
0
0
0
Rep
0
A Vouches
0
0
0
Vouches
0
Posts
43
Likes
162
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 300 XP
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/

codeginiter_welcome_4.png

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. `id`

    int

    (

    11

    )

    NOT

    NULL

    AUTO_INCREMENT

    ,
  3. `email`

    varchar

    (

    40

    )

    NOT

    NULL

    ,
  4. `password`

    varchar

    (

    40

    )

    NOT

    NULL

    ,
  5. `fname`

    varchar

    (

    100

    )

    NOT

    NULL

    ,
  6. PRIMARY KEY

    (

    `id`

    )
  7. )

    ENGINE

    =

    InnoDB

    DEFAULT

    CHARSET

    =

    latin1;

  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_config_2.png

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. public

    function

    login(

    $email

    ,

    $password

    )

    {
  8. $query

    =

    $this

    ->

    db

    ->

    get_where

    (

    'users'

    ,

    array

    (

    'email'

    =>

    $email

    ,

    'password'

    =>

    $password

    )

    )

    ;
  9. return

    $query

    ->

    row_array

    (

    )

    ;
  10. }

  11. }
  12. ?>

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. class

    User extends

    CI_Controller {

  4. function

    __construct(

    )

    {
  5. parent::

    __construct(

    )

    ;
  6. $this

    ->

    load

    ->

    helper

    (

    'url'

    )

    ;
  7. $this

    ->

    load

    ->

    model

    (

    'users_model'

    )

    ;
  8. }

  9. public

    function

    index(

    )

    {
  10. //load session library
  11. $this

    ->

    load

    ->

    library

    (

    'session'

    )

    ;

  12. //restrict users to go back to login if session has been set
  13. if

    (

    $this

    ->

    session

    ->

    userdata

    (

    'user'

    )

    )

    {
  14. redirect(

    'user/home'

    )

    ;
  15. }
  16. else

    {
  17. $this

    ->

    load

    ->

    view

    (

    'login_page'

    )

    ;
  18. }
  19. }

  20. public

    function

    login(

    )

    {
  21. //load session library
  22. $this

    ->

    load

    ->

    library

    (

    'session'

    )

    ;

  23. $output

    =

    array

    (

    'error'

    =>

    false

    )

    ;

  24. $email

    =

    $_POST

    [

    'email'

    ]

    ;
  25. $password

    =

    $_POST

    [

    'password'

    ]

    ;

  26. $data

    =

    $this

    ->

    users_model

    ->

    login

    (

    $email

    ,

    $password

    )

    ;

  27. if

    (

    $data

    )

    {
  28. $this

    ->

    session

    ->

    set_userdata

    (

    'user'

    ,

    $data

    )

    ;
  29. $output

    [

    'message'

    ]

    =

    'Logging in. Please wait...'

    ;
  30. }
  31. else

    {
  32. $output

    [

    'error'

    ]

    =

    true

    ;
  33. $output

    [

    'message'

    ]

    =

    'Login Invalid. User not found'

    ;
  34. }

  35. echo

    json_encode

    (

    $output

    )

    ;
  36. }

  37. public

    function

    home(

    )

    {
  38. //load session library
  39. $this

    ->

    load

    ->

    library

    (

    'session'

    )

    ;

  40. //restrict users to go to home if not logged in
  41. if

    (

    $this

    ->

    session

    ->

    userdata

    (

    'user'

    )

    )

    {
  42. $this

    ->

    load

    ->

    view

    (

    'home'

    )

    ;
  43. }
  44. else

    {
  45. redirect(

    '/'

    )

    ;
  46. }

  47. }

  48. public

    function

    logout(

    )

    {
  49. //load session library
  50. $this

    ->

    load

    ->

    library

    (

    'session'

    )

    ;
  51. $this

    ->

    session

    ->

    unset_userdata

    (

    'user'

    )

    ;
  52. redirect(

    '/'

    )

    ;
  53. }

  54. }

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. $(document).on('click', '#clearMsg', function(){
  74. $('#responseDiv').hide();
  75. });
  76. });
  77. </script>
  78. </body>
  79. </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 :)


Download
You must upgrade your account or reply in the thread to view hidden text.
 

452,292

323,526

323,535

Top