My ajax login form does not work on codeigniter

advertisements

I have written login form in CodeIgniter. it submits the information to the database when I write wrong data it gives me errors and validation errors which I want. But when I write right username and pass and press LOG IN it just does nothing, but when I refresh the page it shows that I am logged in. I want it to redirect the main page immediately after I press login. I think that the problem is in ajax or controller, but I don't know exactly. Because when I press log in with the correct username and pass it shows nothing in the console.

Here is my view:

<div id="loginmsg"></div>

                    <?php $attributes = array('class' => 'rex-forms', 'name' => 'loginform', 'id' => 'loginform'); ?>
                  <?= form_open_multipart('user/login', $attributes); ?>
                      <div class="form-group">
                          <input name="usernameforlog" id="usernameforlog" type="text" class="form-control" placeholder="Имя пользователя">
                      </div>
                      <div class="form-group">

                          <input name="passwordforlog" id="passwordforlog" type="password" class="form-control" placeholder="Пароль">
                      </div>
                      </div>
                      <div class="modal-footer">
                    <button type="submit" name="submitforlog" class="rex-bottom-medium rex-btn-icon btnsubmitforlog">
                        <span class="rex-btn-text">войти</span>
                        <span class="rex-btn-text-icon"><i class="fa fa-arrow-circle-o-right"></i></span>
                    </button>
                  </div>
                    </form>

here is my controller (I commented redirect line because it doesn't work):

public function login(){
            $data['title'] = 'Sign In';

        $validator = array('success' => false, 'messages' => array());

        $validate_data = array(
            array(
                'field' => 'usernameforlog',
                'label' => 'username',
                'rules' => 'trim|required|alpha_dash'
            ),
            array(
                'field' => 'passwordforlog',
                'label' => 'password',
                'rules' => 'trim|required|md5'
            )
        );

        $this->form_validation->set_rules($validate_data);
        $this->form_validation->set_error_delimiters('<p class="text-danger">', '</p>'); 

            if ($this->form_validation->run() === FALSE)
            {
                // fails
                $validator['success'] = false;
                foreach ($_POST as $key => $value) {
                    $validator['messages'][$key] = form_error($key);
                }
            }else {

                // Get username
                $username = $this->input->post('usernameforlog');
                // Get and encrypt the password
                $password = $this->input->post('passwordforlog');
                // Login user
                $user_id = $this->user_model->login($username, $password);
                if($user_id){
                    // Create session

                    $user_data = array(
                        'instructor_id' => $instructor_id,
                        'id' => $id,
                        'instructors_slug' => $username,
                        'name' => $name,
                        'logged_in' => true
                        );

                    $this->session->set_userdata($user_data);
                    $validator['success'] = true;
                    $validator['messages'] = array();
                    //redirect('');
                } else {

                    $validator['success'] = false;
                    $validator['messages'] = '<div class="alert alert-danger text-center">Неверный логин или пароль</div>';
                }
            }

            echo json_encode($validator);
        }

and here is my model:

public function login($username, $password) {
            //validate
            $this->db->where('instructors_slug', $username);
            $this->db->where('password', $password);
            $result = $this->db->get('instructors');

            if($result->num_rows() == 1){
                return $result->row(0)->id;
            } else {
                return false;
            }
        }

and here is ajax file:

$(document).ready(function() {
    $("#loginform").unbind('submit').bind('submit', function() {
        var form = $(this);

        $.ajax({
            url: form.attr('action'),
            type: form.attr('method'),
            data: form.serialize(),
            dataType: 'json',
            success:function(response) {
            console.log(response);
                if(response.success) {
                    //i want here to redirect main page

                }
                else {
                    $("#loginmsg").html(response.messages);

                    $.each(response.messages, function(index, value) {
                        var element = $("#"+index);

                        $(element)
                        .closest('.form-group')
                        .removeClass('has-error')
                        .removeClass('has-success')
                        .addClass(value.length > 0 ? 'has-error' : 'has-success')
                        .find('.text-danger').remove();

                        $(element).after(value);

                    });
                }
            } // /success
        });  // /ajax

        return false;
    });
});


The problem is in your array when you setting session.

Not defined variables $instructor_id, $id etc

  $user_data = array(
                    'instructor_id' => $instructor_id,
                    'id' => $id,
                    'instructors_slug' => $username,
                    'name' => $name,
                    'logged_in' => true
                    );