In my Codeigniter I have a filter option on my web page, here am trying to fetch data from database by jQuery AJAX. Table data retrieve successfully done but datatable not working properly. I am trying with this code.
My HTML code:
<table class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%"> <thead> <tr> <th>SL NO</th> <th>Name</th> <th>Description</th> <th>Value</th> </tr> </thead> <tbody id="FetchReprot"> <tr> <td> </td> <td> </td> <td> </td> </tr> </tbody> </table>
My Controller code:
<?php public function FetchProjectReprot(){ $select_data=$this->db->select('*')->from('my_table')->get()->result_array(); $view=""; $i=1; foreach ($select_data as $pdata) { $view=$view."<tr><td>".$i."</td>"; $view=$view."<tr><td>".$pdata['name']."</td>"; $view=$view."<td>".$pdata['description']."</td>"; $view=$view."<td>".$pdata['vlaue']."</td>"; $view=$view."</tr>"; $i++; } echo $view; } ?>
My JS code:
<script> function FetchProjectReprot(){ var id=$('#id').val(); $.ajax({ type: 'post', url: site_url+'/GetReport', data: {id:id}, success: function(result){ //console.log(result); $('#FetchReprot').html("").html(result); } }); } </script>
Help me, please.
Use DataTable() function while data call by AJAX and give a table id, for example:
Apply code in HTML:
<table id="MyTable" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%"> <thead> <tr> <th>SL NO</th> <th>Name</th> <th>Description</th> <th>Value</th> </tr> </thead> <tbody id="FetchReprot"> <tr> <td> </td> <td> </td> <td> </td> </tr> </tbody> </table>
Apply code in Controller:
<?php public function FetchProjectReprot(){ $select_data=$this->db->select('*')->from('my_table')->get()->result_array(); // Define a blank array variable $returnArray=array(); if(sizeof($select_data)>0){ foreach ($select_data as $pdata) { array_push($returnArray,array('name'=>$pdata['name'],'description'=>$pdata['description'],'value'=>$pdata['value'])); } } header("Content-type:application/json"); echo json_encode($returnArray); } ?>
Ajax:
<script> function FetchProjectReprot(){ var id=$('#id').val(); $.ajax({ type: 'post', url: site_url+'/GetReport', data: {id:id}, success: function(result){ //console.log(result); var t = $('#MyTable').DataTable(); t.clear().draw(); var counter = 1; for(var i=0; i< result.length; i++) { t.row.add([i+1,result[i]['name'],result[i]['description'],result[i]['value']] ).draw( false ); counter++; } } }); } </script>
Hope it will be helpful for you.
Question and answer is powered by AnsPress.io