jeeva jeeva - 4 months ago 132
Javascript Question

I want to pass id from view to controller in Codeigniter using Ajax and Update a Dropdown Selection in DB

I wanted to pass ID of each row from table and pass it to controller using AJAX and wanted to update the Dropdown Selection of that row in DB.

The Selection what i make in Dropdown is passed to the controller but not sure how to update in DB based on its each row condition. A help would be much Appreciated!!!

Below is the Screenshot of my UI

Screen Shot with ID and Dropdown

Screen Shot with ID and Dropdown

View File

<?php if( is_array( $fbrecords ) && count( $fbrecords ) > 0 )
foreach($fbrecords as $r) { ?>
<tr class="idrow">
<td id="tdname" ><!-- style="display:none;" --> <?php echo $r->id; ?></td>
<td><?php echo $r->fullname; ?></td>
<td><?php echo $r->email; ?></td>
<td><?php echo $r->mobile; ?></td>
<td><?php echo $r->message; ?></td>
<td><?php echo $r->jtime; ?></td>
<td> <?php $data=array(

'name'=>'status',
'row' => '12px',
'id' => 'status',
'selected'=>'none',
'class'=>'statusClass'

);
$data_status = array(
'none' => 'none',
'A&A' => 'Attended & Acted',
'YTA' => 'Yet to Attend',
);
echo form_dropdown($data, $data_status, set_value('status')); ?> </td>
<td><button type="button" class="btn btn-sm btn-success emlbtn" > Reply to <?php $fname=explode(" ",$r->fullname); echo $fname[0]; ?></button>


AJAX Code

$(document).ready( function() {
$(".statusClass").change(function(event) {
event.preventDefault();
//var dropDown = document.getElementById("status");
//var status = dropDown.options[dropDown.selectedIndex].value;
var status = $(this).val();
console.log(status);
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/user_authentication/user_data_status_submit",
dataType: 'json',
data: {status:status},
success: function(data){
if (result)
{
alert("success");
}
}

});
});
});


Controller

public function user_data_status_submit(){

$data = array(
'status' => $this->input->post('status'),
'id'
);
//Either you can print value or you can send value to database
echo json_encode($data);
$this->login_database->feedback_update($data);

}


Update Function in Model

public function feedback_update($data){

$this->db->set($data);
$this->db->where("id", $old_id);
$this->db->update('feedback_table', $data);

}

Answer

First change your $data array() like this :

 $data = array(
 'data-user' => $r->id, //ID of the row
 'name'=>'status',
 'row' => '12px',
 'id' => 'status',
 'selected'=>'none',
'class'=>'statusClass'
);

Your ajax should be like this way:

  $(".statusClass").each(function(index, element) {
    $(this).on('change', function(e) {
        var id = $(this).data('user');
        var status = $(this).val(); 
        console.log(id);
        console.log(status);
        // your ajax stuff go as usual
    });
});