Adin Ramdhan
Adin Ramdhan

Reputation: 29

Create jQuery autocomplete with codeigniter

I want to create jquery autocomplete with Codeigniter with data as below :

$data = Array
(
    [0] => Array
        (
            [name] => Pencil
            [id] => 111
        )

    [1] => Array
        (
            [name] => Paper
            [id] => 112
        )

    [2] => Array
        (
            [name] => Stappler
            [id] => 113
        )

    [3] => Array
        (
            [name] => Cutter
            [id] => 114
        )

)

My controller :

public function search_product() {
    if (count($data > 0)) {
        $json_array = array();
        for ($s = 0; $s < count($data); $s++) {
            $json_array[] = array("name"=>$data[$s]['name'], "id"=>$data[$s]['id']);
        }
        echo json_encode($json_array);
    }
}

Javascript code :

$(document).ready(function () {
        $(function () {
            $( "#autocomplete" ).autocomplete({
                source: function(request, response) {
                    $.ajax({ 
                        url: "<?php echo base_url('search_product'); ?>",
                        data: { bahasa: $("#autocomplete").val()},
                        dataType: "json",
                        type: "POST",
                        success: function(data){
                            response(data);
                        }    
                    });
                },
                select: function (event, ui) {
                  $('#autocomplete').val(ui.data.name); // display the selected text
                  $('#code').val(ui.data.id); // save selected id to input
                  return false;
                },
            });
        });
    });

My view :

<div id="body">
    Text: <input type="text" id="autocomplete" />
</div>
<div id="body">
    Text: <input type="text" id="code" />
</div>

But autocomplete still not working.

Upvotes: 0

Views: 968

Answers (3)

Mitesh Rathod
Mitesh Rathod

Reputation: 1059

For autocomplete i have use Typeahead Autocomplete JS. please refer this link Typeahead JS

Include Typeahead css and js file

<!-- add JS And CSS for Typeahead Autocomplete -->
<link href="assets/css/jquery.typeahead.min.css" rel="stylesheet" />
<script src="<?php echo base_url(); ?>assets/js/jquery.typeahead.min.js" type="text/javascript"></script>

View file, create search textbox

<!-- View -->
<div class="search_bar_header">
    <div class="typeahead__container">
        <div class="typeahead__field">
            <div class="typeahead__query">
                <input type="search" name="add_autocomplete" class="form-control search_input" id="add-autocomplete" placeholder="Search by destination, tour or attraction " autocomplete="off" />

                <input type="hidden" name="autocomplete" id="field-autocomplete">
                <div class="search_btn">
                    <i class="fa fa-search"></i>
                </div>
            </div>
        </div>
    </div>
</div>

JS Script

$(document).ready(function () {
    var baseurl = "<?php echo base_url() ?>";
    if (jQuery('input#add-autocomplete').length > 0) {

        $.typeahead({
            input: '#add-autocomplete',
            minLength: 1,
            order: "asc",
            maxItem: 12,
            dynamic: true,
            filter: false,
            delay: 500,
            template: function (query, item) {
                return '<span>'+item.package_name+'</span>'
            },
            emptyTemplate: "no result for {{query}}",
            source: {
                packages: {
                    display: "package_name",
                    ajax: function (query) {
                        return {
                            type: "POST",
                            url: baseurl + "home/getCountryAutocomplete",
                            path: "data.packages",
                            data: {
                                query: "{{query}}"
                            },
                            callback: {
                                done: function (data) {
                                    return data;
                                }
                            }
                        }
                    }
                },
            },
            callback: {
                onClick: function (node, a, item, event) {
                    // onclick do something
                }
            },
            debug: true
        });
    }
});

In Controller,

public function getCountryAutocomplete()
{
    $json = array();
    $status = true;
    $query = $this->input->post('query');

    $result = $this->home_model->getGlobalSearch($query);

    if (!empty($result)) {
        foreach ($result as $key => $element) {
            $json[] = array(
                'package_id' => $element['package_id'],
                'package_name' => $element['package_name'],
            );
        }
    } else {
        $status = false;
    }

    $this->output->set_header('Content-Type: application/json');
    echo json_encode(array(
        "status" => $status,
        "error"  => null,
        "data"   => array(
            "packages" => $json,
        )
    ));
}

In Model,

public function getGlobalSearch($data)
{
    $this->db->select(array('id', 'sortname', 'name'));
    $this->db->from('countries');
    $this->db->where('status', '1');
    $this->db->like('name', $data, 'both');
    $country = $this->db->get()->result_array();
}

I hope it will help you :)

Upvotes: 2

Mansi
Mansi

Reputation: 153

The below code works as desired :-

Controller

public function search_product() {
        $post = $this->input->post();       
        if(isset($post['bahasa']) && !empty($post['bahasa'])){
            $data = $this->parents_model->fetchStationery($post['bahasa']);
            echo json_encode($data);
        }
    }

Model

public function fetchStationery($term){
        $response = array();
        $this->db->select('*');
        $this->db->where("name like '%".$term."%' ");
        $records = $this->db->get('stationery')->result();
        foreach($records as $row ){
           $response[] = array("value"=>$row->id,"label"=>$row->name);
        }       
        return $response;        
    }

View

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>    
        <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <div id="body">
        Text: <input type="text" id="autocomplete" />
    </div>
    <div id="body">
      Text: <input type="text" id="code" />
    </div>

Javascript Code

<script>
            $(document).ready(function () {            
                $( "#autocomplete" ).autocomplete({
                    source: function(request, response) {
                        $.ajax({ 
                            url: "<?php echo base_url('home2/search_product'); ?>",
                            data: { bahasa: request.term},
                            dataType: "json",
                            type: "POST",
                            success: function(data){
                                response(data);
                            }    
                        });
                    },
                    select: function (event, ui) {
                        $('#autocomplete').val(ui.item.label);
                        $('#code').val(ui.item.value);
                        return false;
                    }
                });
        });
        </script>

Upvotes: 0

Hasta Dhana
Hasta Dhana

Reputation: 4719

Try to modify your javascript codes like this :

$(function () {
  $("#autocomplete").autocomplete({
    source: function (request, response) {
      $.ajax({
        url: "<?php echo base_url('search_product'); ?>",
        data: {
          bahasa: request.term
        },
        dataType: "json",
        type: "POST",
        success: function (data) {
          response(data);
        }
      });
    },
    select: function (event, ui) {
      $('#autocomplete').val(ui.item.name); // display the selected text
      $('#code').val(ui.item.id); // save selected id to input
      return false;
    },
  });
});

And to get the posted keyword, use the $_POST['bahasa'] variable on your controller query codes.

Upvotes: 0

Related Questions