Currently I have a table in my view class that is populated with data from the backend using MVC framework in codeigniter. Now I have a dropdown above each column that is filling in the same records from my database. So I want to be able to filter my records as soon as the person clicks the item in the dropdown list.
I know how to filter records when a submit button is clicked, but I want this filtering to happen in live time as soon as the user clicks the dropdown item, for which I'm assuming I'll need to make an AJAX call which I'm not familiar with.
So far I have this in my view class:
<table>
<tr>
<th width="10%">Source</th>
</tr>
<tr>
<td width="5%"><select>
<option value="">All </option>
<?php if($sources) foreach($sources as $source): ?>
<option value="<?php echo $source['title'] ?>"><?php echo $source['title'] ?></option>
<?php endforeach;?>
</select></td>
</tr>
<tbody>
<?php
if(isset($records) && count($records) > 0)
{
foreach($records as $row ){
?>
<tr>
<td><?= $row->source ?></td>
</tr>
<?php } } ?>
</tbody>
Here default the select shows Any with a null value to show all records, and the backend data have thier separate values underneath. Now I want to have a live filtering here. Additionally here I have included only 1 dropdown, but there are multiple dropdowns, so it should make the filtering according to all the dropdown values provided.
CodePudding user response:
Just create an ajax function to receive the request when the option change:
$route['ajax_dropdown'] = 'your_controller/your_function'; // change ajax_dropdown to whatever you want
Then in your controller:
function your_function()
{
$input_value = $this->input->get('your_input_name'); // get the input value of jQuery's get request
$data = array(); // store data in here
// do something like: $data['status'] = $this->your_model->get_status();
echo json_encode($data); // json_encode to make your data object become a string to send }
Finally, in your view you can send ajax request to get data. i prefer to use jQuery so I write it here:
<table>
<tr>
<th width="10%">Source</th>
</tr>
<tr>
<td width="5%">
<select id="your_id_name">
<option value="">All </option>
<?php if ($sources) foreach ($sources as $source) : ?>
<option value="<?php echo $source['title'] ?>"><?php echo $source['title'] ?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
<tbody>
<?php
if (isset($records) && count($records) > 0) {
foreach ($records as $row) {
?>
<tr>
<td><?= $row->source ?></td>
</tr>
<?php }
} ?>
</tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$('#your_id_name').on('change', function() {
$.get('<?php echo base_url('ajax_dropdown'); ?>', {
your_input_name: 'your_value' // input value of get request
}, function(res) {
var values = JSON.parse(res); // then do something
})
})
</script>