In codeigniter How to redirect after login using ajax In codeigniter How to redirect after login using ajax codeigniter codeigniter

In codeigniter How to redirect after login using ajax


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.


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.


Check your return data type. May be you can use in datatype in Ajax code. Return data can't read if condition. I am facing same problem or use this

if($.trim(msg) == 'Yes') {