Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
jQuery autocomplete example
  • Hi, Example of how to use jQuery autocomplete with Fuel. There are two controllers because I extended the Controller_Template you don't have to. Controller 1 - Search
    <?php
    
    /**
     * The Search Controller.
     *
     * file: fuel/app/classes/controller/search.php
     *
     * Associated files:
     * fuel/app/classes/controller/lookup.php
     *
     * fuel/app/views/search/search.php
     * fuel/app/views/template.php
     *
     * Author: Weztec Limited (Phil)
     *
     * --
     * -- Cut down example table structure for table `gazetteer`
     * --
     * CREATE TABLE IF NOT EXISTS `gazetteer` (
     *  `id` int(11) NOT NULL AUTO_INCREMENT,
     *  `town` varchar(100) NOT NULL,
     *  `county` varchar(50) NOT NULL,
     *  PRIMARY KEY (`id`)
     * ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
     *
     *
     * Give the user a search facility that is dynamic via jQuery autocomplete and ajax
     *
     *
     * @package  app
     * @extends  Controller_Template
     */
    class Controller_Search extends Controller_Template &#123;
    
     /**
      * The index action.
      *
      * @access  public
      * @return  void
      */
     public function action_index()
     &#123;
         $counties = DB::select('*')
       ->from('gazetteer')
       ->as_object()
       ->execute();
    
         $data['counties_dropdown'] = array('' => 'Select a county'); // Initialise
    
         foreach ($counties as $county)
         &#123;
      $data['counties_dropdown'][$county->county] = $county->county;
         }
    
         $this->template->title = 'Search Page';
         $this->template->content = View::factory('search/search', $data);
     }
    
    }
    
    /* End of file search.php */
    

    Controller 2 - lookup
    <?php
    
    /**
     * The Lookup Controller.
     *
     * file: fuel/app/controller/lookup.php
     *
     * Author: Weztec Limited (Phil)
     *
     * Note:
     * Had to use another controller that does not extend the Template controller
     * The Template controller insists on having values set for title and content
     *
     * Called via ajax from the Search controller
     * response json encoded array
     * 
     * @package  app
     * @extends  Controller
     */
    class Controller_Lookup extends Controller &#123;
    
     /**
      * The index action.
      * 
      * @access  public
      * @return  json encoded array
      */
     public function action_index()
     &#123;
         // Note:
            // the e() function is just a wrapper for htmlentities
            $result = DB::select()->from('gazetteer')->where('town', 'LIKE', e(Input::post('term')).'%')->limit(10)->as_object()->execute();
    
            $data['response'] = 'true';
            $data['message'] = array();
    
            foreach($result as $row)
            &#123;
              $data['message'][] = array( 'label'=> $row->town . ' - ' . $row->county,
                                          'value'=> $row->town,
                                          'county'=>$row->county);
            }
    
            $this->response->body = \Format::forge($data)->to_json();
     }
    }
    
    /* End of file lookup.php */
    

    The view - search
    <?php
    /*
    *
    * file: fuel/app/views/search/search.php
    *
    * Author: Weztec Limited (Phil)
    *
    * Security, browser and development framework compatibility note:
    * Use POST to communicate with the controllers processing the requests
    * This means that ajax must be used as the native jQuery autocomplete uses GET
    *
    */
    ?>
    [removed]
      $(function() &#123;
       $("#town").autocomplete(&#123;
        minLength: 2,
                    source: function(req, add)
                    &#123;
                        $.ajax(&#123;
                            url: '<?php echo Uri::create("lookup"); ?>',
                            dataType: 'json',
                            type: 'POST',
                            data: req,
                            success:
                                function(data)
                                &#123;
                                    if(data.response =='true')
                                    &#123;
                                        add(data.message);
                                    }
                                }
                        });
                    },
                    select: function(event, ui) &#123;
         $('#town').val(ui.item.town);
                        $('#county').val(ui.item.county);
        }
       });
      });
    [removed]
    
    <?php
    echo Form::open();
    echo Form::label('Town', 'town');
    echo Html::br();
    echo Form::input('town', '', array('id' => 'town'));
    echo Html::br(2);
    echo Form::label('County', 'county');
    echo Html::br();
    echo Form::select('county', 'none', $counties_dropdown, array('id' => 'county'));
    echo Html::br(2);
    echo Form::submit('submit', ' Search ');
    echo Form::close();
    

    The Template
    <?php
    /*
    * file: fuel/app/views/template.php
    *
    * Author: Weztec Limited (Phil)
    */
    ?>
    <!DOCTYPE html>
    <html>
    <head>
     <meta charset="utf-8">
     <title><?php echo $title; ?></title>
    
     <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css">;
     [removed]Link to jquery.min.js[removed]
     [removed]Link to jquery-ui.min.js[removed]
    
     <style type="text/css">
      * &#123; margin: 0; padding: 0; }
      body &#123; background-color: #EEE; font-family: sans-serif; font-size: 16px; line-height: 20px; margin: 40px; }
      #wrapper &#123; padding: 30px; background: #fff; color: #333; margin: 0 auto; width: 600px; }
      a &#123; color: #36428D; }
      h1 &#123; color: #000; font-size: 55px; padding: 0 0 25px; line-height: 1em; }
      .intro &#123; font-size: 22px; line-height: 30px; font-family: georgia, serif; color: #555; padding: 29px 0 20px; border-top: 1px solid #CCC; }
      h2 &#123; margin: 50px 0 15px; padding: 0 0 10px; font-size: 18px; border-bottom: 1px dashed #ccc; }
      h2.first &#123; margin: 10px 0 15px; }
      p &#123; margin: 0 0 15px; line-height: 22px;}
      a &#123; color: #666; }
      pre &#123; border-left: 1px solid #ddd; line-height:20px; margin:20px; padding-left:1em; font-size: 16px; }
      pre, code &#123; color:#137F80; font-family: Courier, monospace; }
      ul &#123; margin: 15px 30px; }
      li &#123; line-height: 24px;}
      .footer &#123; color: #777; font-size: 12px; margin: 40px 0 0 0; }
    
            .ui-autocomplete &#123;
      max-height: 150px;
      overflow-y: auto;
      overflow-x: hidden;
      padding-right: 20px;
            white-space: nowrap;
            font-size: 12px;
         }
         * html .ui-autocomplete &#123; /* As per usual IE does not support support something that's in general use in this case it's max-height */
      height: 150px;
         }
     </style>
    </head>
    <body>
     <div id="wrapper">
      <h1><?php echo $title; ?></h1>
            <?php echo $content; ?>
      <p class="footer">
       <a href="http://fuelphp.com">Fuel PHP</a> is released under the MIT license.<br />Page rendered in &#123;exec_time}s using &#123;mem_usage}mb of memory.
      </p>
     </div>
    </body>
    </html>
    

    Phil.
  • Thanks Phil.
  • Hello, is there any chance that you can share all these different files via http://scrp.at ? other than that - thanks a lot!
  • Hi, ScrapYd Links as requested... Controllers
    Main Controller Controller_Search: http://scrp.at/Mi
    Secondary AJAX Controller_Lookup: http://scrp.at/Mj Views
    Search view: http://scrp.at/Mk
    Template view: http://scrp.at/Ml Phil.
  • Cheers fella!
    BN
  • Nice tutorial +

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion