javascriptdatabasecodeigniterautocompletedouble-submit-problem

Codeigniter Autocomplete from Database


I have some problems in my project. I am trying to do autocomplete with JavaScript in CodeIgniter. I already tried many options, but they don't work!

The controller:

 public function getResult($referencia){
     if(!empty($referencia) || isset($referencia))
     {
        $this->db->like('referencia', $referencia);
        echo json_encode( $this->db->get('produto_servico_tbl')->result());
     }
 }

The autocomplete.js (created by me):

$(document).ready(function(){
    $('#search').keypress(function(e){
        if(e.which == 13)
        {
            e.preventDefault();
        }
        var searched = $('#search').val()
        var fullurl = $('#hiddenurl').val() +    'autoComplete_v.php/autoComplete_c/getResult/' + searched
        $.getJSON(fullurl,function(result){
            //display suggestion code goes here
            var elements = [];
            $.each(result, function(i, val){
                elements.push(val.referencia)
            })
            $('#search').autocomplete({
                source : elements
            })
        })
    })
})

The view:

<head>
<link href="<?=base_url()?>css/ui-lightness/jquery-ui-1.10.3.custom.css" media="screen" type="text/stylesheet" rel="stylesheet" />

<form>
    <label for="search">Search</label>
    <input id="search" type="text"/>
    <input value="<?=base_url()?>" id="hiddenurl" type="hidden">
    <input type="submit" value="submit"/>
</form>

<script src="<?=base_url()?>js/jquery-1.9.1.js" type="text/javascript"></script>
<script src="<?=base_url()?>js/jquery-ui-1.10.3.custom.min.js" type="text/javascript"></script>
<script src="<?=base_url()?>js/jquery-ui-1.10.3.custom" type="text/javascript"></script>
<script src="<?=base_url()?>js/autocomplete.js" type="text/javascript"></script>

Solution

  • You are giving the wrong URL for the AJAX call.

    Change this line:

    var fullurl = $('#hiddenurl').val() +    'autoComplete_v.php/autoComplete_c/getResult/' + searched
    

    Here $('#hiddenurl').val() is your base_url(). So the complete URL will be:

     var fullurl = $('#hiddenurl').val() +    'controller_class_name/getResult/' + searched
    

    In CodeIgniter your URL is like this:

    base_url/controller_class_name/method_name/parameter1/parameter2....
    

    Your autocomplete_v.php will produce an error. You can check how your JavaScript is working with Firebug.