首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在CodeIgniter中使用AJAX返回结果?

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

Stack Overflow用户
提问于 2017-03-05 16:03:13
回答 1查看 142关注 0票数 1

我想问一下如何使用AJAX在我的视图上返回像return 'Password successfully updated';return 'Failed to Update Record';这样的响应。在提交返回响应后,它在没有AJAX的情况下工作得很好。

现在,我只在表单中包含了AJAX,表单运行良好。但提交后未显示错误和成功消息(响应)。

Ajax

代码语言:javascript
复制
 $(document).ready(function(){
    $('form.jsForm').on('submit', function(e){
        e.preventDefault();
        $.post('change_password_process', $('form.jsForm').serialize(), function(data){
            $('div.response').html(data);
        });
    });
});

模型

代码语言:javascript
复制
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!';
    }
}

控制器

代码语言:javascript
复制
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();
    }
}

视图

代码语言:javascript
复制
<?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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-05 16:13:49

在模型中只使用echo而不是return

代码语言:javascript
复制
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!';
    }
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42605958

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档