I am making an autocomplete function. When I type the ID of the user. The other textbox should fetched the name. For example, `
I typed “4” then the other textbox should have the value of
“hwoarang”.
My current function is working for first textbox only. It is not dynamic. Is there a way where i can do it dynamically? I think i need to autoincrement my ID in controller because in Ajax i’m just calling the ID which is only good for 1 textbox.
userid | user | id |
---|---|---|
1 | hwoarang | 4 |
2 | paul | 5 |
Ajax:
$(document).ready(function(){
var list =$('#list').DataTable({ // This is for fetching my data
dom: 'lBfrtip',
buttons: [
'print', 'csv', 'copy', 'excel', 'pdfHtml5'
],columnDefs: [ {
targets: [0,1,2,3,4,5,6,7,8,9,10,11,12],
className: 'bolded'
}
],
"processing": false, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
"paging":false,
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('controller/lists')?>",
"type": "POST",
"data": function ( data ) {
}
},
});
$(document).on('keyup', '#id', function(event){ // This is my autocomplete function
event.preventDefault();
var id= $('.id').val();
$.ajax({
url:"<?=site_url('controller/lists')?>",
method:"GET",
data:{id:id},
dataType:"json",
success:function(data){
$('#id').val(data.id);
$('#user').val(data.user);
}
})
});
});
Controller
public function lists()
{
$list = $this->controller->fetching_function();
$data = array();
$no = $_POST['start'];
foreach ($list as $person1) {
$no++;
$row = array();
$row[] = '<tr><input type="text" style="width:50px; height:20px;" id="user" name="user" ></td>';
$row[] = '<tr><input type="text" style="width:50px; height:20px;" id="id" name="id" ></td>'; // If i type the id "4", then the textbox for name should be "hwoarang"
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->controller->count_all(),
"recordsFiltered" => $this->controller->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
function autocomplete(){
$output=array();
$id=$this->input->get('id');
$data = $this->model->getdetails($id);
foreach($data as $row){
$output['id'] = $row->id;
$output['user'] = $row->user;
}
echo json_encode($output);
}
Model:
function getdetails($id){
$this->db->where('id',$id);
$query=$this->db->get('users');
return $query->result();
}