Welcome Guest, Not a member yet? Register   Sign In
Autocomplete Search in CodeIgniter
#1

(This post was last modified: 01-28-2018, 12:05 PM by sabimofler.)

Hello everyone,

I'm working on a blog project (inspired from traversy media youtube channel) but I want too add more functionality to it. 
At the moment you can search for any item but I am trying to make the idea of 'autocomplete search' to work. 
I have coded the server request from js file, but I don't have a clear idea how can I connect that idea with the following code. 
Can someone help me, please?
Code:
<!-- JavaScript File -->
function showSuggestion(str) {
 if(!str.trim.length > 0) {
   const xmlHttp = new XMLHttpRequest();
   xmlHttp.onreadystatechange = function() {
     if(this.readyState == 4 && this.status == 200) {
       document.getElementById('results').innerHTML = this.responseText;
     }
     xmlHttp.open("GET", `posts/method?q=${str}`, true);
            xmlHttp.send();
   }
 }
}

PHP Code:
<!-- CONTROLLER -->
public function 
search() {
 
 $data['title'] = 'Search Results';

 
 $data['search'] = $this->input->get('query_search');
 
 $searchedPost strtolower($this->input->get('query_search'));

 
 $data['posts'] = $this->Post_model->search_posts($searchedPost);

 
 $this->load->view('templates/header.php');
 
 $this->load->view('posts/search'$data);
 
 $this->load->view('templates/footer.php');

PHP Code:
<!-- MODEL -->
public function 
search_posts($searched_post) {
 
$this->db->like('title'$searched_post);
 
 $this->db->or_like('body'$searched_post);
 
 $this->db->order_by('posts.id''DESC'); 
 
 $this->db->join('categories''categories.id = posts.category_id');
 
 $query $this->db->get('posts');
 
 return $query->result_array();


Code:
<!-- VIEW -->
<form action="<?php echo base_url('posts/search'); ?>" method="GET" class="form-inline my-2 my-lg-0">
 <input class="form-control mr-sm-2" type="text" name="query_search" placeholder="Search"
  oninput="showSuggestion(this.value)">
   <ul id="results">
   </ul>      
 <button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>
</form>
Reply
#2

What about jquery plugin with complete functionality?
Reply
#3

You might just need an onclick event listener to monitor when user click on the suggestions?
Reply




Theme © iAndrew 2016 - Forum software by © MyBB