Chris Lumbberg Chris Lumbberg - 9 days ago 5
jQuery Question

Refresh list after save data using AJAX Codeigniter

Hello I want to insert data into database using AJAX Codeigniter using modal box Bootstrap, I can insert my data into my table, but I found a result not what I want. When I after insert data I want to show my new data in the end of list, the action after save is close the modal then add my list (my lists are checkbox data) but my new list is retrieve entire data from my table. Could you like to solve my problem..Thanks

Here is my controller

function list_type_placement(){
$type_placement=$this->type->get_by('level',1);
if ($type_placement<>0) {
$row=0;
foreach ($type_placement as $key => $value) {
$row++;
echo "
<div class='checkbox' id='rows".$row."'>
<input id=".$value->id_type." type='checkbox' name='id_type[]'' value=".$value->id_type.">
<label for=".$value->id_type.">
".$value->type_name."
</label>
</div>
";
}
}
exit;
}


My View

<div id="placement">
</div>


And this is my ajax action

<script type="text/javascript">
$(document).ready(function(){
list_placement();
});
function list_placement(){
$.ajax({
url:"<?php echo base_url() ?>product/list_type_placement",
type:'GET',
}).done(function(response){
$("#placement").append(response);
});
}
function save(){
$('#btnSave').text('Saving...');
$('#btnSave').attr('disabled',true);

$.ajax({
url : "<?php echo site_url('product/save_placement')?>",
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status)
{
$('#modal-form').modal('hide');
list_placement();
}
}
}).done(function(response){
$("#placement").last().append(response);
});
}
</script>


This is my current output

enter image description here

Answer

You can add new method lists() method for retrieve last single data.

In Controller :

function lists(){
    $this->db->order_by('id_type', 'desc');
    $this->db->limit(1);
    $query = $this->db->get('type_table');  
    $value = $query->row();
    echo "<div class='checkbox' id='rows".$row."'>
            <input id=".$value->id_type." type='checkbox' name='id_type[]'' value=".$value->id_type.">
            <label for=".$value->id_type.">
                ".$value->type_name."
            </label>
         </div>";
}

Now, can some change list_placement() function in your script function.

$("#placement").last().append(response); and change url with lists like url:"<?php echo base_url() ?>product/lists",

In Jquery :

function list_placements(){ 
    $.ajax({ 
        url:"<?php echo base_url() ?>product/lists", 
        type:'GET', 
    }).done(function(response){
        console.log(response); 
        $("#placement").last().append(response); 
    }); 
}

Note: Bad practice to write active quqery code in controller, i will better write active query in your model.

Comments