如何在CodeIgniter中使用AJAX返回结果?

时间:2017-03-05 08:03:13

标签: ajax codeigniter

我想问一下如何使用AJAX在我的视图中返回return 'Password successfully updated';return 'Failed to Update Record';之类的响应。在提交返回响应后,没有AJAX之前它工作正常。

现在我只是在我的表单上包含AJAX,表单工作正常。但提交后没有显示错误和成功消息(响应)。

的Ajax

 $(document).ready(function(){
    $('form.jsForm').on('submit', function(e){
        e.preventDefault();
        $.post('change_password_process', $('form.jsForm').serialize(), function(data){
            $('div.response').html(data);
        });
    });
});

模型

public function updatePassword($data){ //update user password
    $oldPassword = $data['oldPassword'];
    $user = $data['user'];

    $this->db->select('password')
             ->from('users')
             ->where('username', $user);
    $query = $this->db->get();
    $row = $query->row();

     if($this->bcrypt->check_password($oldPassword, $row->password)){
        if($this->db->set('password', $data['newPassword'])
                        ->where('username', $user)
                        ->update('users')){
            return 'Password successfully updated';
        } else {
            return 'Failed to Update Record';
        }

    } else {
        return 'Old password is incorrect!';
    }
}

控制器

if($this->form_validation->run() == TRUE){

        $data = array(
                'user' => $this->input->post('username'),
                'oldPassword' => $this->input->post('oldPassword'),
                'newPassword' => $this->bcrypt->hash_password($this->input->post('newPassword')),
                'cPassword' => $this->input->post('cPassword')
        );

        //this is the response from MODEL 

     $this->session->set_flashdata('response',$this->user_accounts_model->updatePassword($data)); 
        //redirect('user_accounts/change_password_form');

    } else {
        $this->change_password_form();
    }
}

查看

<?php if($response = $this->session->flashdata('response')) :?>

    <div class="alert alert-dismissible alert-success">
      <?=$response?>
    </div>
<?php endif; ?> //this is the form result w/out ajax

<div class="response"></div> //this is using ajax

1 个答案:

答案 0 :(得分:3)

仅在模型echo而不是return

if($this->db->set('password', $data['newPassword'])
                        ->where('username', $user)
                        ->update('users')){
            echo 'Password successfully updated';
        } else {
            echo 'Failed to Update Record';
        }

    } else {
        echo 'Old password is incorrect!';
    }