简体   繁体   中英

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???

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') {

Change echo "Yes"; to die("Yes"); . This will make sure nothing will be sent after "Yes" or "No" and then the JS code will work as expected.

Their is also a way to redirect from your controller after success. In this case you just need to follow these two steps to redirect This line in your controller where you get true condition and want to redirect

if($result){     
      echo base_url()."welcome/";  
    }  
    else{  
       echo 0;  
    }  

on your html page where you applied your ajax, on true condition you try this to redirect page

success: function(result){  
            if(result!=0){  
                // On success redirect.  
            window.location.replace(result);  
            }  
            else  
                alert('wrong'); 
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM