weixin_33725126 2016-10-10 07:26 采纳率: 0%
浏览 40

如何使用Ajax登录

I am quite new to JS and AJAX and I am having a hard time understanding what the other person has implemented and how I can get it to function properly.

This is my login CI code that is working perfectly, but now I want to do it with AJAX:

class Login extends Admin_Controller {
    public function index() {
        if ($this->session->userdata('user')) {
            return redirect('admin/dashboard');
        }
        $this->form_validation->set_rules('txtemail', 'Email', 'required');
        $this->form_validation->set_rules('txtpassword', 'Password', 'required');
        if ($this->form_validation->run() == TRUE) {
            $username = $this->input->post('txtemail');
            $password = $this->input->post('txtpassword');
            $query = $this->database_model->GetRecord('cms_users', false, array('EmailAddress' => $username, 'Password' => $password));
            if ($query == false) {
                $this->session->set_flashdata('display_msg', 'Invalid Username/Password.');
                return redirect('admin/login');
            } else {
                $this->session->set_userdata('user', $query);
                return redirect('admin/dashboard');
            }
        } else {
            $this->load_view('admin/login');
        }
    }
}

And this is my JS:

var options = {
    success: function() {
        window.location = 'admin/master_templete';
    },
    error: function() {
        alert('Thanks for error comment!');
    }
};
$(document).ready(function(){
    $('#form_login').validate({
        errorElement: 'span',
        errorClass: 'error',
        focusInvalid: false,
        ignore: "",
        rules: {
            email: {
                required: true,
                email: true
            },
            password: {
                required: true
            }
        },
        messages: {
            email: 'Please enter email address',
            password: 'Please enter password'
        },
        errorPlacement: function (error, element) { // render error placement for each input type
            error.insertAfter(element.next());
        },
        submitHandler: function (form,status) {
            $('#form_login').ajaxSubmit(options);
            return false;
        }
    });
});
  • 写回答

4条回答 默认 最新

  • weixin_33686714 2016-10-10 07:36
    关注

    instead of redirecting for successful response return redirect('admin/dashboard'); you should send JSON success message and on client-side you should check if you have received a success msg and then redirect to 'admin/dashboard'

    评论

报告相同问题?