简体   繁体   中英

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:

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

 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'); and the value $id will be = 10

The issue you have is that your ID is not an available key in your POST . You would need to define {id : id} . However, I think this makes more sense from an MVC approach:

$.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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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