dqu3974 2016-12-30 11:48
浏览 35
已采纳

使用Ajax编辑登录配置文件

I'm new to CodeIgniter and need some help :). I managed to build a CRUD functions with ajax over some tutorials and I can Edit, Add new, Delete all user shown on my page. What I want now is when i Login with a user I just want the Logged in Profile to be Edited, not others. Please if someone can help me how can I manage to do that. Thank You in Advance.

Employee.php Controller

<?php

defined('BASEPATH') OR exit('No direct sripct access allowed');

Class Employee extends CI_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->model('Employee_m', 'm');
    }


function index()
{
    $this->load->view('employee/index');

}

public function showAllEmployee()
{
    $result = $this->m->showAllEmployee();
    echo json_encode($result);
}

public function add_user()
{
    $result = $this->m->add_user();
    $msg['success'] = false;
    $msg['type'] = 'add';
    if ($result) {
        $msg['success'] = true;
    }
    echo json_encode($msg);
}

public function edit_user()
{
    $result = $this->m->edit_user();
    echo json_encode($result);
}

public function update_user()
{
    $result = $this->m->update_user();
    $msg['success'] = false;
    $msg['type'] = 'update';
    if ($result) {
        $msg['success'] = true;
    }
    echo json_encode($msg);
}

public function delete_user()
{
    $result = $this->m->delete_user();
    $msg['success'] = false;
    if ($result) {
        $msg['success'] = true;
    }
    echo json_encode($msg);
}

Employee_m Model

<?php defined('BASEPATH') OR exit('No direct sripct access allowed');
class Employee_m extends CI_Model
{

public function showAllEmployee()
{

    $query = $this->db->get('users');
    if ($query->num_rows() > 0){
        return $query->result();
    }
    else
    {
        return false;
    }
}


public function add_user()
{
    $field = array(
        'firstname' => $this->input->post('txtFirstName'),
        'lastname' => $this->input->post('txtLastName'),
        'username' => $this->input->post('txtUsername'),
        'user_email' => $this->input->post('txtUserEmail'),
        'user_password' => $this->input->post('txtUserPassword')
    );
    $this->db->insert('users',$field);
    if ($this->db->affected_rows() > 0){
        return true;
    }else{
        return false;
    }
}

public function get_id(){
    $id = $this->input->get('id');
    $this->db->where('id',$id);
    $query = $this->db->get('users');
    if ($query->num_rows() > 0){
        return $query->result();
    }
    else
    {
        return false;
    }
}


public function update_user()
{
    $id = $this->input->post('txtId');
    $field = array(
        'firstname' => $this->input->post('txtFirstName'),
        'lastname' => $this->input->post('txtLastName'),
        'username' => $this->input->post('txtUsername'),
        'user_email' => $this->input->post('txtUserEmail'),
        'user_password' => $this->input->post('txtUserPassword')
    );
    $this->db->where('id',$id);
    $this->db->update('users',$field);
    if ($this->db->affected_rows() > 0){
        return true;
    }else{
        return false;
    }
}

function delete_user()
{
    $id = $this->input->get('id');
    $this->db->where('id',$id);
    $this->db->delete('users');
    if ($this->db->affected_rows() > 0){
        return true;
    }else{
        return false;
    }
}

}

Index View

<?php $this->load->view('components/page_head'); ?>

<?php
if (isset($this->session->userdata['logged_in'])) {
    $username = ($this->session->userdata['logged_in']['username']);
    $id = ($this->session->userdata['logged_in']['id']);

} else {
    header("location: user_authentication");
}
?>

<div class="col-sm-9">
    <div class="alert alert-success" style="display: none;">

    </div>
<button id="btnAdd" class="btn btn-success">Add New</button>
<table class="table table-bordered table-responsive" style="margin-top: 20px;">
    <thead>
    <tr>
        <td>ID</td>
        <td>First Name</td>
        <td>Last Name</td>
        <td>Username</td>
        <td>e-Mail</td>
        <td>Actions</td>
    </tr>
    </thead>
    <tbody id="showdata">

    </tbody>
</table>

<div id="myModal" class="modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">Modal title</h4>
            </div>
            <div class="modal-body">
                <form id="myForm" action="" method="post" class="form-horizontal">
                    <input type="hidden" name="txtId" value="0">
                    <div class="form-group">
                        <label class="label-control col-md-4">First Name</label>
                        <div class="col-md-6">
                            <input type="text" name="txtFirstName" class="form-control">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="label-control col-md-4">Last Name</label>
                        <div class="col-md-6">
                            <input type="text" name="txtLastName" class="form-control">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="label-control col-md-4">Username</label>
                        <div class="col-md-6">
                            <input type="text" name="txtUsername" class="form-control">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="label-control col-md-4">e-Mail</label>
                        <div class="col-md-6">
                            <input type="email" name="txtUserEmail" class="form-control">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="label-control col-md-4">Password</label>
                        <div class="col-md-6">
                            <input type="password" name="txtUserPassword" class="form-control" placeholder="******">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" id="btnSave" class="btn btn-primary">Save changes</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<div id="deleteModal" class="modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">Confirm Delete</h4>
            </div>
            <div class="modal-body">
                Do you want to delete this record?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" id="btnDelete" class="btn btn-danger">Delete</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<script>
    $(function () {
        showAllEmployee();

        // Add New
        $('#btnAdd').click(function () {
            $('#myModal').modal('show');
            $('#myModal').find('.modal-title').text('Add new user');
            $('#myForm').attr('action','<?php echo base_url() ?>employee/add_user');
        });

        $('#btnSave').click(function () {
//            alert('test');
            var url = $('#myForm').attr('action');
            var data = $('#myForm').serialize();

            // validate the form
            var firstname = $('input[name=txtFirstName]');
            var lastname = $('input[name=txtLastName]');
            var username = $('input[name=txtUsername]');
            var user_email = $('input[name=txtUserEmail]');
            var user_password = $('input[name=txtUserPassword]');
            var result = '';
            if (firstname.val()==''){
                firstname.parent().parent().addClass('has-error');
            }else {
                firstname.parent().parent().removeClass('has-error');
                result +='1';
            }
            if (lastname.val()==''){
                lastname.parent().parent().addClass('has-error');
            }else {
                lastname.parent().parent().removeClass('has-error');
                result +='2';
            }
            if (username.val()==''){
                username.parent().parent().addClass('has-error');
            }else {
                username.parent().parent().removeClass('has-error');
                result +='3';
            }
            if (user_email.val()==''){
                user_email.parent().parent().addClass('has-error');
            }else {
                user_email.parent().parent().removeClass('has-error');
                result +='4';
            }
            if (user_password.val()==''){
                user_password.parent().parent().addClass('has-error');
            }else {
                user_password.parent().parent().removeClass('has-error');
                result +='5';
            }


            if(result == '12345'){
                $.ajax({
                    type: 'ajax',
                    method: 'post',
                    url: url,
                    data: data,
                    async: false,
                    dataType: 'json',
                    success: function (response) {
                        if (response.success){
                            $('#myModal').modal('hide');
                            $('#myForm')[0].reset();
                            if(response.type=='add'){
                                var type = 'added'
                            }else if(response.type=='update'){
                                var type ="updated"
                            }
                            $('.alert-success').html('User '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
                            showAllEmployee();
                        }else{
                            alert('Error');
                        }
                    },
                    error: function () {
                        alert('Could not add Data ');
                    }
                });
            }
        });

        //edit
        $('#showdata').on('click', '.item-edit', function() {

            var id = $(this).attr('data');
            $('#myModal').modal('show');
            $('#myModal').find('.modal-title').text('edit user');
            $('#myForm').attr('action','<?php echo base_url() ?>employee/update_user');
            $.ajax({
                type: 'ajax',
                method: 'get',
                url: '<?php echo base_url() ?>employee/edit_user',
                data: {id: id},
                async: false,
                dataType: 'json',
                success: function(data) {
                    $('input[name=txtFirstName]').val(data.firstname);
                    $('input[name=txtLastName]').val(data.lastname);
                    $('input[name=txtUsername]').val(data.username);
                    $('input[name=txtUserEmail]').val(data.user_email);
                    $('input[name=txtUserPassword]').val(data.user_password);
                    $('input[name=txtId]').val(data.id);
                },
                error: function() {
                    alert('Could not Edit Data');
                }
            });
        });

        //delete
        $('#showdata').on('click', '.item-delete', function () {
            var id = $(this).attr('data');
            $('#deleteModal').modal('show');
            $('#btnDelete').unbind().click(function () {
                $.ajax({
                    type: 'ajax',
                    method: 'get',
                    async: false,
                    url: '<?php echo base_url() ?>employee/delete_user',
                    data: {id: id},
                    dataType: 'json',
                    success: function (response) {
                        if(response.success){
                            $('#deleteModal').modal('hide');
                            $('.alert-success').html('User deleted successfully').fadeIn().delay(4000).fadeOut('slow');
                            showAllEmployee();
                        }else{
                            alert('Error');
                        }
                    },
                    error: function () {
                        alert('Error deleting');
                    }
                });
            });
        });

        //function
        function showAllEmployee() {
            $.ajax({
                type: 'ajax',
                url: '<?php echo base_url() ?>employee/showAllEmployee',
                async: false,
                dataType: 'json',
                success: function (data) {
                    var html = '';
                    var i;
                    for (i = 0; i < data.length; i++) {
                        html += '<tr>' +
                            '<td>'+data[i].id+'</td>'+
                            '<td>' + data[i].firstname + '</td>' +
                            '<td>' + data[i].lastname + '</td>' +
                            '<td>' + data[i].username + '</td>' +
                            '<td>' + data[i].user_email + '</td>' +
                            '<td>' +
                            '<a href="javascript:;" class="btn btn-info item-edit" data="'+data[i].id+'">Edit</a>' +
                            '<a href="javascript:;" class="btn btn-danger item-delete" data="'+data[i].id+'">Delete</a>' +
                            '</td>' +
                            '</tr>';
                    }
                    $('#showdata').html(html);
                },
                error: function () {
                    alert('Could not get Data from Database');
                }
            });
        }
    });
</script>
</div>
<div class="col-sm-3">
    <?php
    echo "Hello <b id='welcome'><i>" . $username . "</i> !</b>";
    echo "<br/>";
    echo "Your ID is " . $id;
    echo "<br/>";
    ?>
    <a href="<?php echo base_url() ?>user_authentication/logout">Logout</a>
</div>
<?php $this->load->view('components/page_tail'); ?>
  • 写回答

1条回答 默认 最新

  • dpylt7626401 2016-12-30 13:46
    关注

    You need to fetch that user details to index page to avoid edting for other or need to set some condition such as passing users id on edit check if it same as edit id and then proceed for edit opertaion or else return some message

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作