0

I am new to codeigniter and trying to build a login system. My controllers and my model are working fine, the only issue is that the url changes and appears to be domainName/controller/function which I don't like so I googled and made an AJAX function, but then when I'm adding AJAX, the function always returns the error function and not the success function part.

My View

<!-- <form class="login100-form validate-form" method="POST" action="<?php echo base_url(); ?>welcome/login_validation"> -->
                <form class="login100-form validate-form" method="POST" id="login">
                    <span class="login100-form-title">Member Login</span>

                    <div class="text-center">
                        <span class="text-danger"><?php echo $this->session->flashdata("error"); ?></span>  
                    </div>

                    <div class="wrap-input100 validate-input" data-validate="Valid email is required: ex@abc.xyz">
                        <input class="input100" type="email" name="email" id="email" placeholder="Email" value="<?php echo set_value('email'); ?>" >
                        <span class="focus-input100"></span>
                        <span class="symbol-input100">
                            <i class="fa fa-envelope" aria-hidden="true"></i>
                        </span>
                        <span class="text-danger"><?php echo form_error('email'); ?></span>
                    </div>

                    <div class="wrap-input100 validate-input" data-validate="Password is required">
                        <input class="input100" type="password" name="password" id="password" placeholder="Password" value="<?php echo set_value('password'); ?>">
                        <span class="focus-input100"></span>
                        <span class="symbol-input100">
                            <i class="fa fa-lock" aria-hidden="true"></i>
                        </span>
                        <span class="text-danger"><?php echo form_error('password'); ?></span>
                    </div>

                    <div class="container-login100-form-btn">
                        <button class="login100-form-btn" type="submit">Login</button>
                    </div>

                    <div class="text-center p-t-12">
                        <span class="txt1">Forgot</span>
                        <a class="txt2" href="">Username / Password?</a>
                    </div>

                    <!-- <div class="text-center p-t-136">
                        <a class="txt2" href="#">
                            Create your Account
                            <i class="fa fa-long-arrow-right m-l-5" aria-hidden="true"></i>
                        </a>
                    </div> -->
                </form>

My Controller

class Welcome extends CI_Controller {
    public function login_validation(){
            $this->load->library('form_validation');
            $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email', array(
                'required' => '%s feild cannot be empty',
                'valid_email' => 'Please Enter a Valid Email'
            ));
            $this->form_validation->set_rules('password', 'Password', 'required');

            if($this->form_validation->run()){
                $email = $this->input->post('email');
                $password = $this->input->post('password');

                $this->load->model('main_model');
                // $data['can_login'] = $this->main_model->login($email, $password);
                echo json_encode($data);

                //With Session
                if($this->main_model->login($email, $password)){
                    $user_session = array(
                        "email" =>  $email
                    );
                    $this->session->set_userdata($user_session);
                    redirect(base_url() . 'welcome/check_user_session');

                }
                else{
                    $this->session->set_flashdata('error', 'Invalid Email or Password');
                    $this->index();
                }
            }
            else{
                $this->index();
            }
        }

        public function check_user_session(){
            if($this->session->userdata('email') != ''){
                // echo $this->session->userdata('email');
                redirect(base_url() . 'welcome/user_info');
            }
            else{
                redirect(base_url() . 'welcome/index');
                $this->session->set_flashdata('error', 'Your are already loged in');
            }
        }
}

My Model

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

class Main_model extends CI_Model{

    public function login($email, $password){
        $this->db->where("email", $email);
        $this->db->where("password", $password);
        $can_login = $this->db->get("users");

        if($can_login->num_rows() > 0){
            return true;
        }
        else{
            return false;
        }
    }
}

?>

My AJAX function

<script type="text/javascript">
        $(document).ready(function(){
            $('#login').submit(function(e){
                e.preventDefault();
                // var user_email = $('#email').val();
                var user_email = $("input[name='email']").val();
                var user_password = $('#password').val();

                $.ajax({
                    method: 'POST',
                    url: '<?php echo base_url(); ?>welcome/login_validation',
                    dataType: 'json',
                    // data: new FormData(this),
                    data: {
                        email: user_email,
                        password: user_password
                    },
                    contentType: false,
                    processData: false,

                    success: function(res){
                        alert(res);
                        alert('Loged In');

                    },
                    error: function(data){
                        //alert('Unsuccessful');
                        console.log(data);
                    }
                });
            });
        });
    </script>
Romi Halasz
  • 1,949
  • 1
  • 13
  • 23
  • Storing passwords in plain text is a bad idea – Rotimi Feb 14 '20 at 10:52
  • What's returning in the error function? – Cadu De Castro Alves Feb 14 '20 at 11:19
  • @Akintunde-Rotimi I know but this is only for a testing purpose – Nehal Abubakar Feb 14 '20 at 11:42
  • @CaduDeCastroAlves The ajax is going to a error function which first alerts(unsuccessful) and the second alerts [object object1]. – Nehal Abubakar Feb 14 '20 at 11:44
  • Could you please console.log() the error? You should be more specific. – Cadu De Castro Alves Feb 14 '20 at 11:46
  • @CaduDeCastroAlves the thing that i was alerting like alert(data) i have changed to console.log(data) but that isn't displaying anything on the console. – Nehal Abubakar Feb 14 '20 at 12:53
  • Hey @NehalAbubakar , Please tell me exact error , when you click the Login Button !, and also check log. – Rahul Kr Daman Feb 14 '20 at 12:58
  • Hi @BloodyProgrammer, The thing is that in the error: function(data) when doing alert(data) so it's alerting [object object1] but when i'm doing console.log(data) so it's displaying no error or anything in the console. – Nehal Abubakar Feb 14 '20 at 13:06
  • ajax wont get a response if you are not showing value as a response like this `echo json_encode($data);` see this post https://stackoverflow.com/questions/38688963/how-to-receive-a-ajax-response-from-a-codeigniter-controller –  Feb 14 '20 at 13:18
  • @Dlk I had tried that also but there was no error msg found in the console so had commented that just resuming it to be more specific – Nehal Abubakar Feb 14 '20 at 14:08
  • You better see this for an example how to get response from php https://stackoverflow.com/a/59594761/12232340 –  Feb 14 '20 at 19:42

1 Answers1

0

The main issue (and there may be others) is what you do in the controller.

A function that responds to an ajax request must return something to the server. Your ajax setup expects to get JSON back from the server. But you seem to be trying (depending on circumstances) to load a view (i.e. '$this->index();') or to redirect to a different page. Neither of these two actions is appropriate for a function that is handling an ajax request.

login_validation() should probably do only one thing

echo json_encode($data);

Where $data['can_login'] is set to either true or false.

Back at $ajax.success: you respond accordingly.

If you want to redirect you will have to use javascript to get that done.

DFriend
  • 8,869
  • 1
  • 13
  • 26