Diasline
Diasline

Reputation: 635

Insert checked checkbox value in database and remove it when unchecked

I am trying to apply this purpose in my project, I have a table that display checkbox values from a table. My goal is to insert checked value to another table and remove it when I unchecked it from this table.

I made an insertion like this :

1- table

 <table>

foreach($result as $row)
{
 <tr>
<td><?=$row->name?></td>
<td><input type='checkbox' class="check-lab" value="   
<?=$row->id?>"  /></td>
</tr>
<?php } ?>
</table>

2- JQUERY

$('.check-lab').change(function() {
if ($(this).is(':checked')) {
var labCheckded= $(this).val();
var deleteLab= 1;
}

else {
var deleteLab= 0;

}

$.ajax({
type:'POST',
url:'<?=base_url('admin_medico/SaveLab')?>',
data: {labCheckded:labCheckded,deleteLab:deleteLab},
success:function(data) {

},

});

})

3- CONTROLLER

public function SaveLab(){

$save = array(
  'laboratory'  => $this->input->post('labCheckded')
 );
$this->model_admin->SaveLab($save);

}

AFTER CHECKING, SOME VALUES INSERTIONS ARE MADE PROPERLY. HOW CAN I REMOVE (DELETE) IT IF I UNCHECKED THIS VALUE ?

Upvotes: 0

Views: 811

Answers (1)

95faf8e76605e973
95faf8e76605e973

Reputation: 14191

Your code is already fine you just need to create a new model and controller for deleting the item.
Example:

In your jQuery, do:

    $('.check-lab').change(function() {

    var labCheckded= $(this).val();

    if ($(this).is(':checked')) {
    var deleteLab= 1;
    $.ajax({
    type:'POST',
    url:'<?=base_url('admin_medico/SaveLab')?>',
    data: {labCheckded:labCheckded,deleteLab:deleteLab},
    success:function(data) {
    },
    });
    } 

    else {
    var deleteLab= 0;
    $.ajax({
    type:'POST',
    url:'<?=base_url('admin_medico/DeleteLab')?>',
    data: {labCheckded:labCheckded,deleteLab:deleteLab},
    success:function(data) {
    },
    });
    }

    });

In your controller you could have

public function DeleteLab(){
$delete = array(
  'laboratory'  => $this->input->post('labCheckded')
 );
$this->model_admin->DeleteLab($delete);
}

In your model you could have function

public function DeleteLab($delete){
    $this->db->where('column_name', $delete['laboratory']); //assuming $delete['laboratory'] is a proper key
    $this->db->delete('table_name');
}

Upvotes: 1

Related Questions