0

I'm trying to build a CodeIgniter jQuery ajax login system with Bootstrap theme. I want to compare the value entered from the admin to login with the value from database and when they didn't match, it will prompt an error with no page refresh. Any help and suggestions is much appreciated. Thanks.

Here's my code:

readyLogin.js

var ReadyLogin = function () {

return {
    init: function () {

        /* Login form - Initialize Validation */
        $('#form-login').validate({
            errorClass: 'help-block shake animated', // You can change the animation class for a different entrance animation - check animations page
            errorElement: 'div',
            errorPlacement: function (error, e) {
                e.parents('.form-group > div').append(error);
            },
            highlight: function (e) {
                $(e).closest('.form-group').removeClass('has-success has-error').addClass('has-error');
                $(e).closest('.help-block').remove();
            },
            success: function (e) {
                e.closest('.form-group').removeClass('has-success has-error');
                e.closest('.help-block').remove();
            },
            rules: {
                'login-username': {
                    required: true
                },
                'login-password': {
                    required: true,
                    minlength: 5
                }
            },
            messages: {
                'login-username': {
                    required: "Please enter Administrator's username."
                },
                'login-password': {
                    required: "Please provide Administrator's password.",
                    minlength: 'Your password must be at least 5 characters long.'
                }
            }
        });
        $("#login-button").click(function(){
            var username = $("#login-username").val();
            var password = $("#login-password").val();

            var postData = {
                'username' : username,
                'password' : password,
                'msg' : 'login'
            };

            $.post('', postData, function(postData) {
                if (postData === 'login') {
                    alert('LOGIN SUCCESSFULL'+data);
                } else {
                    alert('LOGIN FAILED'+data);
                }
            });
        });
    }
};
}();

controller/Login.php

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends CI_Controller {

public function __construct() {
    parent::__construct();
    $this->load->helper('form');
    $this->load->helper('url');
    $this->load->helper('html');
}

public function index() {
    $data['error'] = 0;
    if ($_POST) {
        $this->load->model('Login_model');
        $username = $this->input->post('login-username', true);
        $password = $this->input->post('login-password', true);
        $user = $this->Login_model->login($username, $password);
        if (!$user && $user == null) {
            $data['error'] = 1;
        } else {    
            $data['error'] = 2;
            $this->session->set_userdata('username', $user['usename']);
            $this->session->set_userdata('password', $user['password']);
            redirect(base_url() . 'Maps');
        }
    }
    $this->load->view('Backend/page_ready_login', $data);
}

function logout() {
    $this->session->sess_destroy();
    redirect(base_url(), 'refresh');
}

}

I validate the inputs when it checks from the model, and if it returns an invalid match, I throw a $data['error'] variable valued 1. Then in the view if $error == 1, it will show an error, but i want to do it in jQuery, because this refreshes the page.

Login_model.php

<?php

class Login_model extends CI_Model {

function login($username,$password){
    $where=array(
        'username'=>$username,
        'password'=>sha1($password)
    );
    $this->db->select()->from('admin')->where($where);
    $query=$this->db->get();
    return $query->first_row('array');
}

}

views/page_comp_ready.php

<?php
include 'assets/Backend/inc/config.php';
$template['title'] = 'BCGIS | LOGIN';
$template['page_preloader'] = true;
?>
<?php include 'assets/Backend/inc/template_start.php'; ?>

<!-- Login Container -->
<div id="login-container">
<!-- Login Header -->
<h1 class="h3 text-light text-center push-top-bottom fadeIn animated">
    <div class="row">
        <div class="col-lg-3 fadeIn animated">
            <img src="<?= base_url(); ?     >assets/Backend/images/Ph_seal_davao_del_norte_panabo_city.png" style="width: 95px; height: 80px;"/>
        </div>
        <div class="col-lg-9 fadeIn animated">
            <strong>Brgy. Cagangohan Geographical Information System</strong>
        </div>
    </div>
</h1>
<!-- END Login Header -->

<!-- Login Block -->
<div class="block fadeIn animated">
    <!-- Login Title -->
    <div class="block-title">
        <h2>Administration Login</h2>
    </div>
    <!-- END Login Title -->

    <!-- Login Form -->
    <form id="form-login" action="<?php echo base_url(); ?>" method="post" class="form-horizontal">
        <?php if ($error == 1) { ?>
            <h5 class="alert alert-danger shake animated">Your Username/Password is incorrect!</h5>
        <?php } ?>
        <div class="form-group">
            <div class="col-xs-12">
                <input type="text" id="login-username" name="login-username" class="form-control" placeholder="Username..">
            </div>
        </div>
        <div class="form-group">
            <div class="col-xs-12">
                <input type="password" id="login-password" name="login-password" class="form-control" placeholder="Password..">
            </div>
        </div>
        <div class="form-group form-actions">
            <div class="col-sm-offset-2 col-sm-8 text-center">
                <center>
                    <button type="submit" id="login-button" name="login-button" class="btn btn-effect-ripple btn-block btn-primary"><i class="fa fa-check"></i> Sign In</button>
                </center>
            </div>
        </div>
    </form>
    <!-- END Login Form -->
</div>
<!-- END Login Block -->

<!-- Footer -->
<footer class="text-muted text-center fadeIn animated">
    <small><span id="year-copy"></span> &copy; <a href="#"><?php echo       $template['name'] . ' ' . $template['version']; ?></a></small>
</footer>
<!-- END Footer -->
</div>
<!-- END Login Container -->

<?php include 'assets/Backend/inc/template_scripts.php'; ?>

<!-- Load and execute javascript code used only in this page -->
<script src="<?= base_url(); ?>assets/Backend/js/pages/readyLogin.js">     </script>
<script>
$(function () {
    ReadyLogin.init();
});
</script>

<?php include 'assets/Backend/inc/template_end.php'; ?>

2 Answers 2

1

add remote tag to validate using ajax

rules: {
            'login-username': {
                required: true,
                remote: "your function URL"
            },
            'login-password': {
                required: true,
                minlength: 5
            }
        },
        messages: {
            'login-username': {
                required: "Please enter Administrator's username.",
                remote: "your Message"

            },
            'login-password': {
                required: "Please provide Administrator's password.",
                minlength: 'Your password must be at least 5 characters long.'
            }
        }

In the case of server side please write working code(I haven't sufficient knowledge of PHP :)

Sign up to request clarification or add additional context in comments.

7 Comments

did you forget to add a URL in this $.post ajax request: $.post('', postData, function(postData) { ?
i actually add a codeigniter code <?=base_url();?> whereas the callback of the controller. it just like $.post('<?=base_url();?>', postData, function(postData){} and it didn't work. additional suggestion/s for you will deeply appreciated. thanks much
its okay @bipashant , i try your code but sadly it didn't work, i confuse of what i put on the remote: '', the url of the controller or the view?
You should put the controller URL Suppose You've User controller and a function named is_email_available yo should put remote: 'user/is_email_available'
alright, but in the password rules, thus the remote: can be apply?
|
0
 /* Login form - Initialize Validation */
    $('#form-login').validate({
        errorClass: 'help-block shake animated', // You can change the animation class for a different entrance animation - check animations page
        errorElement: 'div',
        errorPlacement: function (error, e) {
            e.parents('.form-group > div').append(error);
        },
        highlight: function (e) {
            $(e).closest('.form-group').removeClass('has-success has-error').addClass('has-error');
            $(e).closest('.help-block').remove();
        },
        success: function (e) {
            e.closest('.form-group').removeClass('has-success has-error');
            e.closest('.help-block').remove();
        },
        rules: {
            'login-username': {
                required: true,
                remote: {
                    url: 'Your controller method',
                    data: {
                        user_name: function () {
                            return $("#YourFieldID").val();
                        }
                    }
                }
            },
            'login-password': {
                required: true,
                minlength: 5
            }
        },
        messages: {
            'login-username': {
                required: "Please enter Administrator's username.",
                remote: 'Your Message'

            },
            'login-password': {
                required: "Please provide Administrator's password.",
                minlength: 'Your password must be at least 5 characters long.'
            }
        },
        submitHandler: function (form) { //You're missing submitHandler
            form.submit();
        }
    });

2 Comments

it doesn't working, i got RangeError: Maximum call stack size exceeded error.
And @bipashant, i got another problem please see this PLEASE and throw some help/suggestions. Thanks advance :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.