Home » Php » php – Can't get an ajax response in Codeigniter

php – Can't get an ajax response in Codeigniter

Posted by: admin February 25, 2020 Leave a comment

Questions:

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: [email protected]">
                        <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>
How to&Answers:

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.