0

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.

1
  • Hi @Adin Ramdhan, are you getting any errors? Commented Dec 19, 2019 at 11:34

3 Answers 3

2

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 :)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your advise, now I can make autocomplete properly.
0

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.

2 Comments

Thank you for your advise. query has been running well, but on input text id="complete", there is no autocomplete suggestions. they give blank result. When I check in console log, there was have result. Please advise. Thank you.
Umm, I don't see an id="complete" input on your code, do you get any error message on your console?
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.