In codeigniter How to redirect after login using ajax

I have a login popup. and i register via 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 with ajax. If the email and password are correct, redirect to any page. If not, then an Error will appear.

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 the user's email and password correctly / incorrectly.

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. He shows "Yes". But I want to redirect to another page why is it showing YES on correct email / password.and On wrong email. This shows NO .

Where am I doing wrong ???

+3


source to share


4 answers


You need to change a few lines of code in the jQuery and Controller function. Here I am adding an updated version of your code. See below:

View (Mod Bootstrap)

<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 the same. On clicking the button, you've written a script that needs to be changed. Will attach after attaching the controller 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 run into any problem.

+3


source


You can use a simple redirect()

(included in url helper) in your code if you want to navigate to another controller / method from within the script. However, this will not alert the user that the login was successful: it is just a redirect.

The correct way to do this would be returning a json file, so instead of echoing 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 response in your ajax call, and some nice warning (in my case, Sweet Alert) like:

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, it will be redirected after a while. But if your json response doesn't have a field redirect, it will just show a warning.

+2


source


Check the return type. Maybe you can use as data in your Ajax code. The returned data cannot be read if the condition is. I am facing the same problem or am using this

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

+2


source


Change echo "Yes";

to die("Yes");

. This ensures that nothing is sent after a Yes or No, and then the JS code works as expected.

+1


source







All Articles