Amazon Best Products with minimum price

Tuesday 4 April 2017

Auto-complete search in codeigniter using Ajax.


The Auto complete search box provides,suggestion when you enter any data into the text field.
In this tutorial, data will be fetched from database and displayed in text box when any one types any data in to the text field.

Nowadays, every web app needs to be easy and simple to use. Instead of using drop-down by select tag.we can create the auto search box which fetches the data from database and display in search box.

1) First we are going to create pages in "View." Let's create the task.php in application/view and load the CDN of bootstrap and Jquery in <head> tag in html page.

<!doctype html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>Pagination</title>
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
</body>
</html>

In the above code, we have loaded the bootstrap CDN , Jquery CDN and jquery_ui CDN for displaying the data in searchbox.
Now, we will create one "form" in <body> tag.
After this,we are going to create one "form" with some textfield, assign the ID or CLASS in text field and call it by Ajax.

<?php
$attributes = array('class' => 'form-horizontal','id'=>'');
echo form_open('', $attributes);
?>
<div class="row">
<div class="col-sm-12">
<div class="col-sm-3">
<div class="input-group">
<span>User Name</span>
<?php echo form_input(['class'=>'form-control autofocus','id'=>'name','name'=>'name')]); ?>
</div>
</div>
<div class="col-sm-3">
<div class="input-group">
<span>Date</span>
<?php echo form_input(['class'=>'form-control autofocus','id'=>'date','name'=>'date']); ?>
</div>
</div>
<div class="col-sm-3">
<div class="input-group">
<span>Task Name</span>
<?php echo form_input(['class'=>'form-control autofocus','id'=>'t_name','name'=>'t_name']); ?>
</div>
</div>
<div class="col-sm-3">
<div class="input-group">
<span>Partner Name</span>
<?php echo form_input(['class'=>'form-control autofocus','id'=>'partner','name'=>'partner']); ?>
</div>
</div>
</div>
<input class="btn btn-primary" type="submit" name="submit" value="submit">
<?php 
echo form_close();
?>

Here in the above code, we have created one form with some text field and assign them ID. Based on the text field ID we called the Ajax and fetched the data from controller and passed it to "View" inside the form text field.

If we write something related to word, you will find here the ajax code which is applied on text field thereby passing the url to controller and catching the data from database and showing it in the textbox.

 $(function(){ 
    $(document).on("keydown.autocomplete","#t_name",function(e){ 
      $(this).autocomplete({ 
      source : '<?php echo base_url();?>task_search',
      selectFirst: true,
          change: function (event, ui) {
           if (ui.item == null){ 
            //here is null if entered value is not match in suggestion list
            $(this).val((ui.item ? ui.item.id : ""));
            }
           } 
      }); 
    }); 
  });

a) In the above Ajax query, we used keydown.autocpmlete which is used for the selecting word to fetch from database and display like dropdown.
b) function (event, ui) is used for selecting only the fetched data from database.If you write you own text then system will show you blank data.

2) Now let's create the controller task_search.php in application/controller.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class task_search extends CI_Controller{ 

public function __construct()
{ 
parent::__construct();
/*Load the task of model*/
$this->load->model('pojo'); 
}


public function index(){

if (!isset($_GET['term']))
{
  exit;
}
  
  $qs = strtolower($this->input->get('term'));     
  $this->pojo->search_task($qs);

} 
}

 a) $this->load->model('pojo'); load the model pojo.

b) $qs = strtolower($this->input->get('term'));    
  $this->pojo->search_task($qs);

 Get the variable from "View" and passed to the model pojo method search_task.

3) Here is the method search_task in application/model/pojo

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class pojo extends CI_Model{  

public function search_task($qs){
  /*comparing data with the text box*/  
  $query = $this->db->query("SELECT t_name FROM task_name WHERE t_name LIKE ('$qs%') ORDER BY t_name LIMIT 5");
  /* It checks the row in database table*/
    if($query->result_id->num_rows > 0)
        {
        foreach ($query->result_array() as $row)
              {
                $row_set[] = htmlentities(stripslashes($row['t_name']));
              }
             echo json_encode($row_set); 
        }       
  }
  }

Above is the logic code, which is used to fetch the data from database and passed by foreach by using json_encode.

That's it from my side, if you have any queries, please feel free to write in the comments down below.

Thank you!!

No comments:

Post a Comment