Обновление и удаление не удаляются автоматически или обновляются после отправки, Codeigniter и Ajax - PullRequest
1 голос
/ 21 марта 2020

Моя проблема в моем обновлении в том, что я могу обновить свои данные, но мне нужно сначала изменить значение текстового поля перед обновлением.

И моя проблема при удалении - я могу удалить свои данные, но мне нужно обновить их sh страница, прежде чем данные будут удалены.

Есть ли какое-нибудь решение для этого?

My View, где я l oop и отображаю мои данные.

// Show Groups
        function showGroups(){
            $.ajax({
                type: 'ajax',
                url: '<?php echo base_url() ?>groups/showGroups',
                async: false,
                dataType: 'json',
                success: function(data){
                    var html = '';
                    var i;
                    for(i=0; i<data.length; i++){
                        html +='<a class="text-decoration-none" href="<?php echo base_url() ?>groups/view_class/'+data[i].id+'">'+
                                    '<div class="col-md-4">'+
                                        '<div class="card" style="width: 15rem; text-align:center;display:inline-block;">'+
                                        '<div class="card-body">'+
                                            '<input type="hidden" name="groupId" value="1" />'+
                                            '<h5 class="card-title">'+data[i].group_name+'</h5>'+
                                            '<h6 class="card-subtitle mb-2 text-muted">Modify your Group</h6>'+
                                            '<a href="javascript:;" class="btn btn-info item-edit" data="'+data[i].id+'"><span class="iconify" data-icon="feather:edit" data-inline="false"></span></a>&nbsp;'+
                                            '<a href="javascript:;" class="btn btn-primary item-delete" data="'+data[i].id+'"><span class="iconify" data-icon="dashicons:remove" data-inline="false"></span></a>'+
                                        '</div>'+
                                        '</div><hr>'+
                                    '</div><hr>'+
                                '</a>';
                    }
                    $('#showdata').html(html);
                },
                error: function(){
                    alert('Could not get Data from Database');
                }
            });
        }

My Edit, чтобы показать мой мод и получить data

//edit
    $('#showdata').on('click', '.item-edit', function(){
            var id = $(this).attr('data');
            $('#myModal').modal('show');
            $('#myModal').find('.modal-title').text('Edit Group');
            $('#myForm').attr('action', '<?php echo base_url() ?>groups/updateGroup');
            $.ajax({
                type: 'ajax',
                method: 'get',
                url: '<?php echo base_url() ?>groups/editGroup',
                data: {id: id},
                async: false,
                dataType: 'json',
                success: function(data){
                    $('input[name=group]').val(data.group_name);
                    $('input[name=txtId]').val(data.id);
                },
                error: function(){
                    alert('Could not Edit Data');
                }
            });
        });

My Update

$('#btnSave').click(function(){
        var url = $('#myForm').attr('action');
        var data = $('#myForm').serialize();
        //validate form
        var group = document.getElementById('group').value;

        if(group.replace(/\s/g, "").length <=0 ) {
            swal("Submission fail!", "Enter the required field", "error");
            return false;
        }

            $.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'
                        }

                        swal("Success!", "You delete a Question!", "success");                          
                        showGroups();
                    }else{
                        alert('Error');
                    }
                },
                error: function(){
                    alert('Could not add data');
                }
            });

    });

My Delete

    //delete- 
    $('#showdata').on('click', '.item-delete', function(){
        var id = $(this).attr('data');
        $('#deleteModal').modal('show');
        //prevent previous handler - unbind()
        $('#btnDelete').unbind().click(function(){
            $.ajax({
                type: 'ajax',
                method: 'get',
                async: false,
                url: '<?php echo base_url() ?>groups/deleteGroup',
                data:{id:id},
                dataType: 'json',
                success: function(response){
                    if(response.success){
                        $('#deleteModal').modal('hide');
                        swal("Success!", "You delete a Group!", "success"); 
                        showGroups();
                    }else{
                        alert('Error');
                    }
                },
                error: function(){
                    alert('Error deleting');
                }
            });
        });
    });

Контроллер

public function showGroups(){
    $result = $this->group_model->showGroups();
    echo json_encode($result);
}

Наконец, модель

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

public function updateGroup(){
    $id = $this->input->post('txtId');
    $field = array(
    'group_name'=>$this->input->post('group')
    );
    $this->db->where('id', $this->user_id);
    $this->db->update('groups', $field);
    if($this->db->affected_rows() > 0){
        return true;
    }else{
        return false;
    }
}

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

public function editGroup(){
    $result = $this->group_model->editGroup();
    echo json_encode($result);
}

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

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

1 Ответ

1 голос
/ 21 марта 2020

Не перезагружайте страницу для Ajax Процесс, который вы можете удалить конкретный div, используя идентификатор Обновите ваш javascript следующим образом

// Show Groups
        function showGroups(){
            $.ajax({
                type: 'ajax',
                url: '<?php echo base_url() ?>groups/showGroups',
                async: false,
                dataType: 'json',
                success: function(data){
                    var html = '';
                    var i;
                    for(i=0; i<data.length; i++){
                        html +='<a class="text-decoration-none" href="<?php echo base_url() ?>groups/view_class/'+data[i].id+'" id="group_'+data[i].id+'">'+ // Here i added id to remove using  unique id 
                                    '<div class="col-md-4">'+
                                        '<div class="card" style="width: 15rem; text-align:center;display:inline-block;">'+
                                        '<div class="card-body">'+
                                            '<input type="hidden" name="groupId" value="1" />'+
                                            '<h5 class="card-title">'+data[i].group_name+'</h5>'+
                                            '<h6 class="card-subtitle mb-2 text-muted">Modify your Group</h6>'+
                                            '<a href="javascript:;" class="btn btn-info item-edit" data="'+data[i].id+'"><span class="iconify" data-icon="feather:edit" data-inline="false"></span></a>&nbsp;'+
                                            '<a href="javascript:;" class="btn btn-primary item-delete" data="'+data[i].id+'"><span class="iconify" data-icon="dashicons:remove" data-inline="false"></span></a>'+
                                        '</div>'+
                                        '</div><hr>'+
                                    '</div><hr>'+
                                '</a>';
                    }
                    $('#showdata').html(html);
                },
                error: function(){
                    alert('Could not get Data from Database');
                }
            });
        }

В вашей модели & Controller возвращает идентификатор сообщения в ответе

    function deleteGroup(){
        $id = $this->input->get('id');
        $this->db->where('id', $id);
        $this->db->delete('groups');
        if($this->db->affected_rows() > 0){
            return $id;
        }else{
            return false;
        }
    }
public function deleteGroup(){
    $result = $this->group_model->deleteGroup();
    $msg['success'] = false;
    if($result){
        $msg['success'] = $result;
    }
    echo json_encode($msg);
}

В вашем ответе Delete javascript удалите определенный div, используя идентификатор ответа

//delete- 
 $('#showdata').on('click', '.item-delete', function(){
    var id = $(this).attr('data');
    $('#deleteModal').modal('show');
    //prevent previous handler - unbind()
    $('#btnDelete').unbind().click(function(){
        $.ajax({
            type: 'ajax',
            method: 'get',
            async: false,
            url: '<?php echo base_url() ?>groups/deleteGroup',
            data:{id:id},
            dataType: 'json',
            success: function(response){
                if(response.success){
                    var id = response.success;
                    $('#group_'+id).remove(); // Here i remove that part 
                    $('#deleteModal').modal('hide');
                    swal("Success!", "You delete a Group!", "success"); 
                    showGroups();
                }else{
                    alert('Error');
                }
            },
            error: function(){
                alert('Error deleting');
            }
        });
    });
});

Надеюсь, это поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...