Auto Complete in CodeIgniter using jquery from database
Expert User
Verified
Autocomplete any text from the data present in the database.
function getUsers($postData){ $response = array(); if(isset($postData['search']) ){ // Select record $this->db->select('*'); $this->db->where("product_name_en like '%".$postData['search']."%' "); $records = $this->db->get('product')->result(); foreach($records as $row ){ $response[] = array("value"=>$row->product_id,"label"=>$row->product_name_en); } }
<!doctype html> <html> <head> <title>How to Autocomplete textbox in CodeIgniter with jQuery UI</title> <!-- jQuery UI CSS --> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"> </head> <body> Search User : <input type="text" id="autouser"> <br><br> Selected user id : <input type="text" id="userid" value='0' > <!-- Script --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- jQuery UI --> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <script type='text/javascript'> $(document).ready(function(){ // Initialize $( "#autouser" ).autocomplete({ source: function( request, response ) { // Fetch data $.ajax({ url: "<?=base_url()?>/welcome/userList", type: 'post', dataType: "json", delay:0, data: { search: request.term }, success: function( data ) { response( data ); } }); }, select: function (event, ui) { // Set selection $('#autouser').val(ui.item.label); // display the selected text $('#userid').val(ui.item.value); // save selected id to input return false; } }); }); </script> </body> </html>
public function userList(){ // POST data $postData = $this->input->post(); // Get data $data = $this->main_model->getUsers($postData); echo json_encode($data); } return $response; }
It will search the data from the tables and display the list of matching text in the textbox. In this, I have used ajax to autocomplete the text from the tables inside the database.
Please find the code in right-hand side.
Comments
Leave a Comment