Thursday 31 January 2013

Codeigniter autocomplete with php, json, mysql

JQuery Autocomplete in Codeigniter php using JSON.


Autocomplete with multi select. You just need to configure your codeigniter properly, then create a view page, Controller page and a Model page. In Codeigniter we are having directory specified for all the related pages.

This code is for that who is having the basic knowledge of CodeIgniter.

Click here for core php

View Code
 


<!-- Jquery Packages -->

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>

<!-- Jquery Package End -->

<script type="text/javascript">

$(document).ready(function(){
    $(function() {
function split( val ) {
                return val.split( /,\s*/ );
        }
                function extractLast( term ) {
                 return split( term ).pop();
        }

        $( "#txtinput" )
            // don't navigate away from the field on tab when selecting an item
              .bind( "keydown", function( event ) {
                if ( event.keyCode === $.ui.keyCode.TAB &&
                        $( this ).data( "autocomplete" ).menu.active ) {
                    event.preventDefault();
                }
            })
            .autocomplete({
                source: function( request, response ) {
                    $.getJSON( "<?php echo base_url();?>index.php/controller_page/getFunction",{  //Url of controller
                        term: extractLast( request.term )
                    },response );
                },
                search: function() {
                    // custom minLength
                    var term = extractLast( this.value );
                    if ( term.length < 1 ) {
                        return false;
                    }
                },
                focus: function() {
                    // prevent value inserted on focus
                    return false;
                },
                select: function( event, ui ) {
                    var terms = split( this.value );
                    // remove the current input
                    terms.pop();
                    // add the selected item
                    terms.push( ui.item.value );
                    // add placeholder to get the comma-and-space at the end
                    terms.push( "" );
                    this.value = terms.join( "," );
                    return false;
                }
            });
         
});
});

</script>

<!-- Your Input Text Box-->

<input type="text" id="txtinput" size="20" />

<!-- View Code Ended Here---------->

Controller Code


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

class Controller_page extends CI_Controller {
    function __construct()
    {
        parent::__construct();
        $this->load->model(array('model_page'));
    }
   public function getFunction()
    {

if ( !isset($_GET['term']) )
    exit;
    $term = $_REQUEST['term'];
        $data = array();
        $rows = $this->model_page->getData($term); // Model called here
            foreach( $rows as $row )
            {
                $data[] = array(
                    'label' => $row->name.', '. $row->email,
                    'value' => $row->name);   // here i am taking name as value so it will display name in text field, you can change it as per your choice.
            }
        echo json_encode($data);
        flush();

}
}

!-- Controller Code Ended Here---------->

Model Code

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_page extends CI_Model {
    public function __construct()
    {
         parent::__construct();
         // Your own constructor code

    }

    function getData($term) // function called in controller
    {
        $sql = $this->db->query('select * from table_name where name like "'.         mysql_real_escape_string($term) .'%" order by name asc limit 0,10');

return $sql ->result();
    }
}

<!-- Model Code Ended Here---------->

Needed table with name and email.......

Download all files as zip from here..



That's it.

For any issue leave a comment :)

15 comments:

  1. this code is not working for me..please can u provide a working example..this link is not showing

    ReplyDelete
    Replies
    1. hi francee, sorry for late, can you please give me your email id so I can send the whole working code to you in codeigniter...

      Delete
    2. have tried also this code but it still not working , if you don't mind to send your code to my email kanny_mahesa@yahoo.co.id
      I hope you include sql and codeigniter source . thanks ... :)

      Delete
  2. can u please send me the code too ... punitpanchal86@gmail.com.... thanks in advance

    ReplyDelete
  3. hi shashikant, can you share your code to me please.. i got really messy error thank you so much, my email is patience.annajacob@gmail.com thank you so much..

    ReplyDelete
  4. sorry guys I was busy... surely I will send the code..... Wait for 1 more days....

    ReplyDelete
  5. how can i show an image into results?
    Example:
    [img1] - Name 1
    [img2] - Name 2
    [img3] - Name 3

    Thx

    ReplyDelete
  6. hi shashikant, can you share your full example to me please....

    my id :
    amit.dholiya1990@gmail.com
    amit_dholiya@yahoo.com

    ReplyDelete
    Replies
    1. Thank You for send me your code..


      and one another problem with codeignter can you help me?
      without page refresh how can possible pagination library....?
      please help me...

      Delete
    2. check this....
      http://itsmepandey.blogspot.in/2012/08/codeigniter-pagination-with-passing.html

      Delete
    3. with the help of ajax you can do it..

      Delete
    4. This comment has been removed by the author.

      Delete
  7. hi shashikant, can you share your full example to me too. Please

    id
    dhanvela@gmail.com

    Thanks in advance

    ReplyDelete
  8. Hello Shashikant,
    that is an awesome tutorial that you gave. Can you please mail me the working code?
    My email id id sagi.rk08@gmail.com

    ReplyDelete