简体   繁体   English

CodeIgniter:使用AJAX从MySQL数据库删除数据

[英]CodeIgniter: Delete data from MySQL DB using AJAX

I am working on a project, where inside admin panel I have a table for enquiries and I want to allow admin to delete any of them. 我正在一个项目中,在管理面板中我有一个查询表,我想允许管理员删除其中的任何一个。 My view code is as follows: 我的查看代码如下:

<button type="button" class="btn btn-danger delbtn" onclick="delenquiry(<?php echo $value->id;?>)">Delete this Enquiry</button>

My ajax code is: 我的ajax代码是:

function delenquiry(id) {
    if (confirm("Are you sure?")) {
        $.ajax({
            url: base_url + 'loginc/delenq',
            type: 'post',
            data: id,
            success: function () {
                alert('ajax success');
            },
            error: function () {
                alert('ajax failure');
            }
        });
    } else {
        alert(id + " not deleted");
    }
}

Controller code is: 控制器代码为:

 public function delenq() {

        $id = $this->input->post('id');
        $this->logins->delenqs($id);
    }

And model code is: 模型代码是:

public function delenqs($id) {
    $this->db->where('id', $id);
    $this->db->delete('enquiry');

}

I looked for answers, but didn't got any. 我在寻找答案,但没有任何答案。 Can anyone tell me what's wrong with my code. 谁能告诉我我的代码有什么问题。 Thanks in advance... 提前致谢...

You need to pass id from your ajax request change 您需要从ajax请求更改中传递ID

 data: id,

To

 data: {id:id},

for data you must provide an array . 对于数据,您必须提供一个数组。 for example => data:{name_params:10} you can get data in php $id = $this->input->post('name_params'); 例如=> data:{name_params:10}您可以在php中获取数据$id = $this->input->post('name_params'); and the value $id will be = 10 $ id的值= 10

The issue you have is that your ID is not an available key in your POST . 您遇到的问题是,您的ID不是POST的可用密钥。 You would need to define {id : id} . 您将需要定义{id : id} However, I think this makes more sense from an MVC approach: 但是,我认为使用MVC方法更有意义:

$.ajax({
    url: base_url + 'loginc/delenq/'+ id, //maintains the (controller/function/argument) logic in the MVC pattern
    type: 'post',
    success: function(data){
        console.log(data);
    },
    error: function(a,b,c){
        console.log(a,b,c);
    }
});

Then you can expect an argument to your controller function: 然后,您可以为控制器函数指定一个参数:

public function delenq($id){
    if($id)
        return $this->logins->delenqs($id);
    return false;
}

And finally, your model can get a little fixer upper so that it properly returns as well. 最后,您的模型可以使用一些固定器,以便它也可以正确返回。

public function delenqs($id) {
    $this->db->delete('enquiry', array('id' => $id));
    return $this->db->affected_rows() > 1 ? true:false;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM