Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In codeigniter How to redirect after login using ajax

I have a login popup Modal. and i am logging through ajax

Modal

<div class="modal-body">
              <form action="<?php echo base_url('Login');?>" method="POST">
                 <div class="form-group">
                    <input type="text" placeholder="Email or Mobile*" value="" id="loginEmail" name="email" class="form-control input-feild">

                 </div>
                 <div class="form-group">
                    <input type="password" placeholder="Password*" value="" id="loginPassword" name="password" class="form-control input-feild">

                 </div>
                 <div class="form-group">
                    <input type="button" id="l_submit" name="l_submit" value="Login" class="btn btn-primary input-feild">
                 </div>
               </form>
               <p id="error-msg"></p>
            </div>

I am trying to redirect after successful login using ajax. If email and password is correct then redirect to any page. If not then it will show the Error.

Controller

function index() {

        $this->form_validation->set_rules('email', 'Email', 'trim|required');
        $this->form_validation->set_rules('password', 'Password', 'trim|required');

        if ($this->form_validation->run() == false) {
            echo validation_errors();

        }else {
                $email      = $this->input->post("email");
                $password   = $this->input->post("password");
                $user = $this->Perfect_mdl->check_user($email, $password);
                if ($user) {

                    $logged_in_data = array();
                    foreach ($user as $logged_in_data) {
                        $logged_in_data = array(

                                    'id' => $user[0]->id,
                                    'email' => $user[0]->email
                                );
                    }

                    $this->session->set_userdata($logged_in_data);
                    $id = $this->session->userdata('email');
                    $data['details'] = $this->Perfect_mdl->get_login_user_detail($id);

                    echo "Yes";

                }else {

                    echo "No";
                }
        }
    }

This is my controller in which i am checking login user email and password correct/incorrect.

This is my script

 <script type="text/javascript">  
        $("#l_submit").click(function(){

            var email  = $("#loginEmail").val();
            var password   = $("#loginPassword").val();

            $.ajax({
                url : "<?php echo base_url('Login');?>", 
                type: 'POST',
                data : {'email':email,'password':password},
                success: function(msg) {

                        if (msg == "Yes")
                           window.location.href = "<?php echo current_url(); ?>";
                        else if (msg == "No")
                            $('#error-msg').html('<div class="alert alert-danger text-center">Incorrect Email & Password. Please try again ...</div>');
                        else
                            $('#error-msg').html('<div class="alert alert-danger">' + msg + '</div>');
                    }
            });
            return false;
        });
</script>

As you can see in the success part, when i entered the correct email/password. It is showing Yes. But i want to redirect another page, Why this is showing YES on correct email/password.and On incorrect email/password This is showing NO.

Where i am Doing Wrong???

like image 783
Vishal Kumar Avatar asked Jan 05 '23 03:01

Vishal Kumar


2 Answers

You need to change few lines of codes in jQuery and Controller function. Here I am attaching updated version of your code. Please refer below:

View (Bootstrap Modal)

<div class="modal-body">
          <form action="<?php echo base_url('Login');?>" method="POST">
             <div class="form-group">
                <input type="text" placeholder="Email or Mobile*" value="" id="loginEmail" name="email" class="form-control input-feild">

             </div>
             <div class="form-group">
                <input type="password" placeholder="Password*" value="" id="loginPassword" name="password" class="form-control input-feild">

             </div>
             <div class="form-group">
                <input type="button" id="l_submit" name="l_submit" value="Login" class="btn btn-primary input-feild">
             </div>
           </form>
           <p id="error-msg"></p>
        </div>

This is your view file. It will remain same. On clicking on button you have written a script which need to be modified. Will attact after attaching controller's function:

Controller

function index() {
    if (!$this->input->is_ajax_request()) {
        echo 'No direct script is allowed';
        die;
    }
    $this->form_validation->set_rules('email', 'Email', 'trim|required');
    $this->form_validation->set_rules('password', 'Password', 'trim|required');

    if ($this->form_validation->run() == false) {
        $result['status'] = 'error';
        $result['message'] = validation_errors();
    }else {
        $email      = $this->input->post("email");
        $password   = $this->input->post("password");
        $user = $this->Perfect_mdl->check_user($email, $password);
        if ($user) {
            $logged_in_data = array();
            foreach ($user as $logged_in_data) {
                $logged_in_data = array(
                    'id' => $user[0]->id,
                    'email' => $user[0]->email
                );
            }
            $this->session->set_userdata($logged_in_data);
            $id = $this->session->userdata('email');
            $data['details'] = $this->Perfect_mdl->get_login_user_detail($id);
            $result['status'] = 'success';
            $result['message'] = 'Yeah! You have successfully logged in.';
$result['redirect_url'] = base_url();
        }else {
            $result['status'] = 'error';
            $result['message'] = 'Whoops! Incorrect Email & Password. Please try again';
        }
    }
    $this->output->set_content_type('application/json');
    $this->output->set_output(json_encode($result));
    $string = $this->output->get_output();
    echo $string;
    exit();
}

Script

<script type="text/javascript">
$("#l_submit").click(function(){

    var email  = $("#loginEmail").val();
    var password   = $("#loginPassword").val();

    $.ajax({
        url : "<?php echo base_url('Login');?>",
        type: 'POST',
        data : {'email':email,'password':password},
        success: function(resp) {

            if (resp.status == "success")
                window.location.href = resp.redirect_url;
            else
                $('#error-msg').html('<div class="alert alert-danger">' + resp.message + '</div>');
        }
    });
    return false;
});

This is the correct answer. Let me know if you face any issue.

like image 197
Abhishek Singh Avatar answered Jan 08 '23 01:01

Abhishek Singh


You can use a simple redirect() (comes in the url helper) in your code if you want to jump to another controller/method from the script. However, this will not alert the user that the login was successful: it's just a plain redirect.

The proper way to do it would be returning a json file, so instead of echoing a yes or no, use this:

$response['type'] = 'error';
$response['msg'] = 'Login Succesful';
$response['redirect'] = 'http://your-url.com/controller/method';
echo json_encode($response);
die;

Then, you handle the answer in your ajax call, and some good alerting (in my case, Sweet Alert) kinda like this:

success: function(data) {
    if (data.redirect) {
        swal({
            title: '¡Success!',
            text: data.msg,
            timer: 2000,
            type: data.type,
            showConfirmButton: false
        }, function() {
            window.location.href = data.redirect;
        });
    } else {
        swal('¡Error!', data.msg, data.type);
    }
}

So what this code does is that if your json response has a redirect field, will trigger the redirection after a while. But if your json response does not have the field redirect, will just show an alert.

like image 41
Matías Navarro Carter Avatar answered Jan 08 '23 02:01

Matías Navarro Carter